Vue.js 最核心的功能就是组件(Component),从组件的构建、注册到组件间通信,Vue 2.x 提供了更多方式,让我们更灵活地使用组件来实现不同需求。

一、构建组件

1.1 组件基础

一个组件由 template、data、computed、methods等选项组成。需要注意:

  • template 的 DOM 结构必须有根元素
  • data 必须是函数,数据通过 return 返回出去

// 示例:定义一个组件 MyComponent
var MyComponent = {{
data: function () {
return {
// 数据
}
},
template: '<div>组件内容</div>'
}

由于 HTML 特性不区分大小写, 在使用kebab-case(小写短横线分隔命名) 定义组件时,引用也需要使用这个格式如 <my-component>来使用;在使用PascalCase(驼峰式命名) 定义组件时<my-component><MyComponent>这两种格式都可以引用。

1.2 单文件组件.vue

如果项目中使用打包编译工具 webpack,那引入 vue-loader 就可以使用 .vue后缀文件构建组件。
一个.vue单文件组件 (SFC) 示例:


// MyComponent.vue 文件
&lt;template&gt;
&lt;div&gt;组件内容&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
export default {
data () {
return {
// 数据
}
}
}
&lt;/script&gt; &lt;style scoped&gt;
div{
color: red
}
&lt;/style&gt;

.vue文件使组件结构变得清晰,使用.vue还需要安装 vue-style-loader 等加载器并配置 webpack.config.js 来支持对 .vue 文件及 ES6 语法的解析。

进一步学习可参考文章:详解 SFC 与 vue-loader

二、注册组件

2.1 手动注册

组件定义完后,还需要注册才可以使用,注册分为全局和局部注册:


// 全局注册,任何 Vue 实例都可引用
Vue.component('my-component', MyComponent) // 局部注册,在注册实例的作用域下有效
var MyComponent = { /* ... */ }
new Vue({
components: {
'my-component': MyComponent
}
}) // 局部注册,使用模块系统,组件定义在统一文件夹中
import MyComponent from './MyComponent.vue' export default {
components: {
MyComponent // ES6 语法,相当于 MyComponent: MyComponent
}
}

注意全局注册的行为必须在根 Vue 实例 (通过 new Vue) 创建之前发生。

2.2 自动注册

对于通用模块使用枚举的注册方式代码会非常不方便,推荐使用自动化的全局注册。如果项目使用 webpack,就可以使用其中的require.context一次性引入组件文件夹下所有的组件:


import Vue from 'vue'
import upperFirst from 'lodash/upperFirst' // 使用 lodash 进行字符串处理
import camelCase from 'lodash/camelCase' const requireComponent = require.context(
'./components', // 其组件目录的相对路径
false, // 是否查询其子目录
/Base[A-Z]\w+\.(vue|js)$/ // 匹配基础组件文件名的正则表达式
) requireComponent.keys().forEach(fileName =&gt; {
// 获取组件配置
const componentConfig = requireComponent(fileName) // 获取组件的 PascalCase 命名
const componentName = upperFirst(
camelCase(
// 剥去文件名开头的 `./` 和结尾的扩展名
fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
)
) // 全局注册组件
Vue.component(
componentName,
componentConfig.default || componentConfig
)
})

三、组件通信

3.1 父单向子的 props

Vue 2.x 以后父组件用props向子组件传递数据,这种传递是单向/正向的,反之不能。这种设计是为了避免子组件无意间修改父组件的状态。

子组件需要选项props声明从父组件接收的数据,props可以是字符串数组对象,一个 .vue 单文件组件示例如下


// ChildComponent.vue
&lt;template&gt;
&lt;div&gt;
&lt;b&gt;子组件:&lt;/b&gt;{{message}}
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
export default {
name: "ChildComponent",
props: ['message']
}
&lt;/script&gt;

父组件可直接传单个数据值,也可以可以使用指令v-bind动态绑定数据:


// parentComponent.vue
&lt;template&gt;
&lt;div&gt;
&lt;h1&gt;父组件&lt;/h1&gt;
&lt;ChildComponent message="父组件向子组件传递的非动态值"&gt;&lt;/ChildComponent&gt;
&lt;input type="text" v-model="parentMassage"/&gt;
&lt;ChildComponent :message="parentMassage"&gt;&lt;/ChildComponent&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
import ChildComponent from '@/components/ChildComponent'
export default {
components: {
ChildComponent
},
data () {
return {
parentMassage: ''
}
}
}
&lt;/script&gt;

配置路由后运行效果如下:

3.2 子向父的 $emit

当子组件向父组件传递数据时,就要用到自定义事件。子组件中使用 $emit()触发自定义事件,父组件使用$on()监听,类似观察者模式。

子组件$emit()使用示例如下:


// ChildComponent.vue
&lt;template&gt;
&lt;div&gt;
&lt;b&gt;子组件:&lt;/b&gt;&lt;button @click="handleIncrease"&gt;传递数值给父组件&lt;/button&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
export default {
name: "ChildComponent",
methods: {
handleIncrease () {
this.$emit('increase',5)
}
}
}
&lt;/script&gt;

父组件监听自定义事件 increase,并做出响应的示例:


// parentComponent.vue
&lt;template&gt;
&lt;div&gt;
&lt;h1&gt;父组件&lt;/h1&gt;
&lt;p&gt;数值:{{total}}&lt;/p&gt;
&lt;ChildComponent @increase="getTotal"&gt;&lt;/ChildComponent&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
import ChildComponent from '@/components/ChildComponent'
export default {
components: {
ChildComponent
},
data () {
return {
total: 0
}
},
methods: {
getTotal (count) {
this.total = count
}
}
}
&lt;/script&gt;

访问 parentComponent.vue 页面,点击按钮后子组件将数值传递给父组件:

3.3 子孙的链与索引

组件的关系有很多时跨级的,这些组件的调用形成多个父链与子链。父组件可以通过this.$children访问它所有的子组件,可无限递归向下访问至最内层的组件,同理子组件可以通过this.$parent访问父组件,可无限递归向上访问直到根实例。

以下是子组件通过父链传值的部分示例代码:


// parentComponent.vue
&lt;template&gt;
&lt;div&gt;
&lt;p&gt;{{message}}&lt;/p&gt;
&lt;ChildComponent&gt;&lt;/ChildComponent&gt;
&lt;/div&gt;
&lt;/template&gt; // ChildComponent.vue
&lt;template&gt;
&lt;div&gt;
&lt;b&gt;子组件:&lt;/b&gt;&lt;button @click="handleChange"&gt;通过父链直接修改数据&lt;/button&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
export default {
name: "ChildComponent",
methods: {
handleChange () {
this.$parent.message = '来自 ChildComponent 的内容'
}
}
}
&lt;/script&gt;

显然点击父组件页面的按钮后会收到子组件传过来的 message。

在业务中应尽量避免使用父链或子链,因为这种数据依赖会使父子组件紧耦合,一个组件可能被其他组件任意修改显然是不好的,所以组件父子通信常用props$emit

3.4 中央事件总线 Bus

子孙的链式通信显然会使得组件紧耦合,同时兄弟组件间的通信该如何实现呢?这里介绍中央事件总线的方式,实际上就是用一个vue实例(Bus)作为媒介,需要通信的组件都引入 Bus,之后通过分别触发和监听 Bus 事件,进而实现组件之间的通信和参数传递。

首先建 Vue 实例作为总线:


// Bus.js
import Vue from 'vue'
export default new Vue;

需要通信的组件都引入 Bus.js,使用 $emit发送信息:


// ComponentA.vue
&lt;template&gt;
&lt;div&gt;
&lt;b&gt;组件A:&lt;/b&gt;&lt;button @click="handleBus"&gt;传递数值给需要的组件&lt;/button&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
import Bus from './bus.js'
export default {
methods: {
handleBus () {
Bus.$emit('someBusMessage','来自ComponentA的数据')
}
}
}
&lt;/script&gt;

需要组件A信息的就使用$on监听:


// ComponentB.vue
&lt;template&gt;
&lt;div&gt;
&lt;b&gt;组件B:&lt;/b&gt;&lt;button @click="handleBus"&gt;接收组件A的信息&lt;/button&gt;
&lt;p&gt;{{message}}&lt;/p&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
import Bus from './bus.js'
export default {
data() {
return {
message: ''
}
},
created () {
let that = this // 保存当前对象的作用域this
Bus.$on('someBusMessage',function (data) {
that.message = data
})
},
beforeDestroy () {
// 手动销毁 $on 事件,防止多次触发
Bus.$off('someBusMessage', this.someBusMessage)
}
}
&lt;/script&gt;

四、递归组件

组件可以在自己的 template 模板中调用自己,需要设置 name 选择。


// 递归组件 ComponentRecursion.vue
&lt;template&gt;
&lt;div&gt;
&lt;p&gt;递归组件&lt;/p&gt;
&lt;ComponentRecursion :count="count + 1" v-if="count &lt; 3"&gt;&lt;/ComponentRecursion&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
export default {
name: "ComponentRecursion",
props: {
count: {
type: Number,
default: 1
}
}
}
&lt;/script&gt;

如果递归组件没有 count 等限制数量,就会抛出错误(Uncaught RangeError: Maximum call stack size exceeded)。

父页面使用该递归组件,在 Chrome 中的 Vue Devtools 可以看到组件递归了三次:

递归组件可以开发未知层级关系的独立组件,如级联选择器和树形控件等。

五、动态组件

如果将一个 Vue 组件命名为 Component 会报错(Do not use built-in or reserved HTML elements as component id: Component),因为 Vue 提供了特殊的元素 <component>来动态挂载不同的组件,并使用 is 特性来选择要挂载的组件。

以下是使用<component>动态挂载不同组件的示例:


// parentComponent.vue
&lt;template&gt;
&lt;div&gt;
&lt;h1&gt;父组件&lt;/h1&gt;
&lt;component :is="currentView"&gt;&lt;/component&gt;
&lt;button @click = "changeToViewB"&gt;切换到B视图&lt;/button&gt;
&lt;/div&gt;
&lt;/template&gt; &lt;script&gt;
import ComponentA from '@/components/ComponentA'
import ComponentB from '@/components/ComponentB'
export default {
components: {
ComponentA,
ComponentB
},
data() {
return {
currentView: ComponentA // 默认显示组件 A
}
},
methods: {
changeToViewB () {
this.currentView = ComponentB // 切换到组件 B
}
}
}
&lt;/script&gt;

改变 this.currentView的值就可以自由切换 AB 组件:

与之类似的是vue-router的实现原理,前端路由到不同的页面实际上就是加载不同的组件。


要继续加油呢,少年!

来源:https://segmentfault.com/a/1190000016409329

【Vue】详解组件的基础与高级用法的更多相关文章

  1. JAVASCRIPT事件详解-------原生事件基础....

    javaScirpt事件详解-原生事件基础(一)   事件 JavaScript与HTML之间的交互是通过事件实现的.事件,就是文档或浏览器窗口中发生的一些特定的交互瞬间,通过监听特定事件的发生,你能 ...

  2. 详解 javascript中offsetleft属性的用法(转)

    详解 javascript中offsetleft属性的用法 转载  2015-11-11   投稿:mrr    我要评论 本章节通过代码实例介绍一下offsetleft属性的用法,需要的朋友可以做一 ...

  3. shell中echo基础及高级用法详解-渐入佳境

    --作者:飞翔的小胖猪 --创建时间:2021年2月19日 1.1 基础用法 echo命令用来输出文本,在shell脚本中用来输出提示信息用的比较多. 单引号:原样输出所有的内容,不用转义就能输出特殊 ...

  4. 详解Linux运维工程师高级篇(大数据安全方向).

    hadoop安全目录: kerberos(已发布) elasticsearch(已发布)http://blog.51cto.com/chenhao6/2113873 knox oozie ranger ...

  5. 微信小程序组件——详解wx:if elif else的用法

    背景 在学习微信小程序开发wxml页面时,需要使用if,else来判断组件是否进行展示,代码如下 <view wx:if="{{is_login==1}}">成功登录& ...

  6. vue组件详解——组件通信

    每天学习一点点 编程PDF电子书.视频教程免费下载:http://www.shitanlife.com/code 组件之间通信可以用下图表示: 组件关系可分为父子组件通信.兄弟组件通信.跨级组件通信. ...

  7. angular路由详解一(基础知识)

    本人原来是iOS开发,没想到工作后,离iOS开发原来越远,走上了前端的坑.一路走来,也没有向别人一样遇到一个技术上的师傅,无奈只能一个人苦苦摸索.如今又开始填angular的坑了.闲话不扯了.(本人学 ...

  8. VUE详解

    渐进式框架 声明式渲染(无需关心如何实现).组件化开发.客户端路由(vue-router).大规模的数据状态(vuex).构建工具(vue-cli) 全家桶:vue.js+vue-router+vue ...

  9. 【知识详解】JAVA基础(秋招总结)

    JAVA基础 目录 JAVA基础 问:面向过程(POP)和面向对象(OOP)? 问:Python和Java的区别? 问:java的八大基本数据类型? 问:封装继承多态说一下? 问:方法和函数的区别? ...

随机推荐

  1. [Bzoj3743][Coci2015] Kamp【换根Dp】

    Online Judge:Bzoj3743 Label:换根Dp,维护最长/次长链 题目描述 一颗树n个点,n-1条边,经过每条边都要花费一定的时间,任意两个点都是联通的. 有K个人(分布在K个不同的 ...

  2. Ionic App 更新插件cordova-plugin-app-version

    1.安装相关插件 cordova-plugin-file  ,cordova-plugin-file-opener2,cordova-plugin-file-transfer,cordova-plug ...

  3. ajax发送验证码

    $.ajax({     url:url,     type:"POST",     data:data,     dataType:"JSON",     s ...

  4. PAT甲级——A1023 Have Fun with Numbers

    Notice that the number 123456789 is a 9-digit number consisting exactly the numbers from 1 to 9, wit ...

  5. Java Iterator模式

    Iterator迭代器的定义:迭代器(Iterator)模式,又叫做游标(Cursor)模式.GOF给出的定义为:提供一种方法访问一个容器(container)对象中各个元素,而又不需暴露该对象的内部 ...

  6. 使用alibaba的json工具将String类型转为JSONArray类型

    转化流程:先将输入流转为String类型,再使用alibaba的json转换工具,将字符串转化为json数组 SensorDevices sensorDevices = new SensorDevic ...

  7. pytorch dataloader 取batch_size时候 出现bug

    1.RuntimeError: invalid argument 0: Sizes of tensors must match except in dimension 0. Got 342 and 2 ...

  8. LA3177 Beijing Guards

    Beijing Guards Beijing was once surrounded by four rings of city walls: the Forbidden City Wall, the ...

  9. Leetcode434.Number of Segments in a String字符串中的单词数

    统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符. 请注意,你可以假定字符串里不包括任何不可打印的字符. 示例: 输入: "Hello, my name is John" ...

  10. linux在线用户管理

    LINUX是个多用户系统,一旦连接到网络中,它可以同时为多个登录用户提供服务.系统管理员可以随时了解系统中有那些用户,用户都在进行什么操作. 1.查看该系统在线用户 系统管理员若想知道某一时刻用户的行 ...