使用组件的原因: 提高代码可复用性
组件的使用方法
全局注册
html:
- <div id="app" v-cloak>
- <my-component></my-component>
- </div>
JS:
- vue.component('myComponent',{
- template: '<div > 我是一个组件</div>'
- })
- var App = new Vue({
- el: '#app'
- })
优点: 所有的 Vue 实例都可以用
缺点: 权限太大, 容错率降低
局部注册
- <div id="app" v-cloak>
- <my-component></my-component>
- </div>
- var App = new Vue({
- el: '#app',
- components:{
- 'myComponent':{
- template: '<div > 我是一个组件</div>'
- }
- }
- })
3. vue 组件的模板在某些情况下会受到 HTML 标签的限制, 比如 < table > 中只能含有 < tr><td> ,
这些元素, 所以直接在 table 中使用组件是无效的, 此时可以使用 is 属性来挂载组件
<table> <tbody is="my-component"></tbody> </table>
组件使用的技巧
1. 推荐使用小写字母加 进行命名(必须)
2. template 中的内容必须被一个 DOM 元素包括 , 也可以嵌套
3. 在组件的定义中, 除了 template 之外的其他选项 - data,computed,methods
4. data 必须是一个方法
<div id="app" v-cloak> <button-component></button-component> </div> components:{ 'button-component':{ template: '<button @click="count+=1">{{count}}</button>', data: function(){ return { count: 0 } } } }
使用 props 传递数据 父亲向儿子传递数据
1. 在组件中使用 props 来从父亲组件接收参数, 注意, 在 props 中定义的属性, 都可以在组件中直接使用
2. props 来自父级, 而组件中 data return 的数据就是组件自己的数据, 两种情况作用域就是 组件本身, 可以在 template,computed,methods 中直接使用
3. props 的值有两种, 一种是字符串数组, 一种是对象, 本节先只讲数组
4. 可以使用 v-bind 动态绑定父组件来的内容
父组件传数据给子组件
<div id="app" v-cloak> <p > 我是父组件</p> <child-component message="听妈妈的话, 别让她受伤"></child-component> </div> var App = new Vue({ el: '#app', components:{ 'child-component':{ props:['message'], template: '<button>{{message}}</button>' } } })
使用 v-bind 动态绑定父组件来的内容
<div id="app" v-cloak> <input type="text" v-model="message"> <child-component :msg="message"></child-component> </div> var App = new Vue({ el: '#app', data:{message: ''}, components:{ 'child-component':{ props:['msg'], template: '<button>{{msg}}</button>' } } })
效果
input 输入框里的内容会同步到子组件 button 按钮内
image.PNG
单向数据流
解释 : 通过 props 传递数据是单向的, 也就是父组件数据变化时会传递给子组件, 但是反过来不行
目的 : 是尽可能将父子组件解稿, 避免子组件无意中修改了父组件的状态.
应用场景: 业务中会经常遇到两种需要改变 prop 的情况
一种是父组件传递初始值进来, 子组件将它作为初始值保存起来, 在自己的作用域下可以随意使用和修改. 这种情况可以在组件 data 内再声明一个数据, 引用父组件 的 prop
步骤一: 注册组件
步骤二: 将父组件的数据传递进来, 并在子组件中用 props 接收
步骤三: 将传递进来的数据通过初始值保存起来
<div id="app"> <my-component init-count="666"></my-comp> </div> var App = new Vue({ el: '#app', components: { 'my-component': { props: ['init-count'], template: '<div>{{count}}</div>', data: function () { return { count: this.initCount } } } } })
另一种情况就是 prop 作为需要被转变的原始值传入. 这种情况用计算属性就可以了
步骤一: 注册组件
步骤二: 将父组件的数据传递进来, 并在子组件中用 props 接收
步骤三: 将传递进来的数据通过计算属性进行重新计算
通过计算属性动态控制元素的宽度
<div id="app" v-cloak> <input type="text" v-model="width"> <child-component :width="width"></child-component> </div> var App = new Vue({ el: '#app', data:{width: 0 }, components:{ 'child-component':{ props:['width'], template: '<div :style="style"></div>', computed:{ style: function(){ return { width: this.width+'px', height: '20px', background: 'grey' } } } } } })
数据验证
vue 组件中 camelCased (驼峰式) 命名与 keba-bcase(短横线命名)
1. 在 HTML 中, myMessage 和 mymessage 是一致的,, 因此在组件中的 HTML 中使用必须使用 kebab-case(短横线)命名方式. 在 HTML 中不允许使用驼峰!!!
2. 在组件中, 父组件给子组件传递数据必须用短横线. 在 template 中, 必须使用驼峰命名, 若为短横线的命名方式. 则会直接保错.
3. 在组件的 data 中, 用 this.XXX 引用时, 只能是驼峰命名方式. 若为短横线的命名方式, 则会报错.
验证的 type 类型可以是:
• String
• Number
• Boolean
• Object
• Array
• Function
Vue.component ( 'my-compopent', {
props : { // 必须是数字类型 propA : Number , // 必须是字符串或数字类型 propB : [String , Number] , // 布尔值, 如果没有定义, 默认值就是 true propC: { type : Boolean , default : true }, // 数字, 而且是必传 propD: { type: Number , required : true }, // 如果是数组或对象, 默认值必须是一个函数来返回 propE: { type : Array , default : function () { return [] ; } }, // 自定义一个验证函数 propF: { validator : function (value) { return value> 10; } } } })
自定义事件 - 子组件给父组件传递数据
使用 v-on 除了监昕 DOM 事件外, 还可以用于组件之间的自定义事件. JavaScript 的设计模式 一一观察者模式, dispatchEvent 和 addEventListener 这两个方法. Vue 组件也有与之类似的一套模式, 子组件用
on() 来 监昕子组件的事件 . 直接甩代码
第一步: 自定义事件
第二步: 在子组件中用 $emit 触发事件, 第一个参数是事件名, 后边的参数是要传递的数据
第三步: 在自定义事件中用一个参数来接受
<div id="app"> <p > 要买多少个苹果? {{number}}</p> <child-component @change="change"></child-component> </div> var App = new Vue({ el: '#app', data: { number: 200 }, methods: { change: function (value) { this.number = value } }, components: { 'child-component': { data: function () { return { count: 200 } }, template: `<div><button @click="add">+1</button><button @click="reduce">-1</button></div>`, methods: { add: function () { this.count += 1 this.$emit('change', this.count) }, reduce: function () { this.count -= 1 this.$emit('change', this.count) } } } } })
效果:
image.PNG
在组件中使用 v-model
$emit 的代码, 这行代码实际上会触发一个 input 事件, 'input'后的参数就是传递给 v-model 绑定 的属性的值 v-model 其实是一个语法糖, 这背后其实做了两个操作
v-bind 绑定一个 value 属性
v-on 指令给当前元素绑定 input 事件
要使用 v-model, 要做到:
接收一个 value 属性.
在有新的 value 时触发 input 事件
<div id="app"> <p > 您要买多少个苹果? {{number}}</p> <child-component v-model="number"></child-component> </div> var App = new Vue({ el: '#app', data: { number: 200 }, components: { 'child-component': { data:function(){return{count:200}}, template: `<button @click="add">+1</button>`, methods: { add: function () { this.count += 1
---------------------- 注意观察. 这一行, emit 的是 input 事件 ----------------
this.$emit('input', this.count) } } } } })
非父组件之间的通信
可以用一个空的 Vue 实例作为中央事件总线:
var bus = new Vue() // 触发事件 bus.$emit('事件名', 1) // 如果是子组件, this.$root.bus // 监听事件 bus.$emit('事件名', function(id){ // ..... })
代码:
<div id="app"> <my-component></my-component> <child-component></child-component> </div> var App = new Vue({ el: '#app', data: { bus: new Vue() }, components: { 'my-component': { data:function(){ return { text: '我是 A 组件里的 text' } }, template: '<div><button @click="onclick">点我</button></div>', methods:{ onclick: function(){ this.$root.bus.$emit('send',this.text) } } }, 'child-component': { template: '<div > 第二个组件</div>', created: function(){ this.$root.bus.$on('send',function(value){ alert(value) }) } } } })
点击 A 组件里的按, 就会触发 send 事件, 同时把数据发出去, B 组件监听 send 事件, 获取传过来的数据
父链: this.$parent
this.$parent.msg = '数据已经修改了'
子链:
this.$refs 提供了为子组件提供索引的方法, 用特殊的属性 ref 为其增加一个索引
// 给子组件添加 ref 属性 this.formchild = this.$refs.c.msg;
使用 slot 分发内容
什么是 slot(插槽)
为了让组件可以组合, 我们需要一种方式来混合父组件的内容与子组件自己的模板. 这个过程被称为内容分发. vue.js 实现了一个内容分发 API, 使用特殊的'slot' 元素作为原始内容的插槽
编译的作用域
在深入内容分发 API 之前, 我们先明确内容在哪个作用域里编译. 假定模板为:
<child-component> {{ message }} </child-component>
message 应该绑定到父组件的数据, 还是绑定到子组件的数据? 答案是父组件. 组件作用 域简单地说是:
父组件模板的内容在父组件作用域内编译;
子组件模板的内容在子组件作用域内编译.
插槽的用法
父组件的内容与子组件相混合, 从而弥补了视图的不足
混合父组件的内容与子组件自己的模板
单个插槽:
<div id="app"> <child-component>
slot, 接着
</child-component> </div> components: { 'child-component': { template: `<div><slot > 如果父组件没有插入内容, 我就作为默认出现</slot></div>` } }
具名插槽:
模板占位 slot 通过 slot 和 name 属性进行关联
<div id="app"> <child-component> <p slot="header">我是标题</p> <p > 文本内容第一部分</p> <p > 文本内容第二部分</p> <p slot="footer">我是页脚</p> </child-component></div> components: { 'child-component': { template: `<div> <div class="header"> <slot name="header"></slot> </div> <div> <slot></slot> </div> <div class="footer"> <slot name="footer"></slot> </div> </div> ` } }
效果:
image.PNG
作用域插槽:
作用域插槽是一种特殊的 slot, 使用一个可以复用的模板来替换已经渲染的元素 -- 从子组件获取数据 ,template 模板是不会被渲染的
<child-component> <template slot="child" slot-scope="parent"> {{parent.text}} </template> </child-component> components: { 'child-component': { template: ` <div> <slot text="子组件里的 text" name="child"></slot> </div>` } }
Vue 2.5.0 之前, slot-scope 只能写在 template 标签上
访问 slot
通过 this.$slots.(NAME)
mounted:function () { // 访问插槽 var header = this.$slots.header; var text = header[0].elm.innerText; var HTML = header[0].elm.innerHTML; console.log(header) console.log(text) console.log(HTML) }
组件高级用法 - 动态组件
VUE 给我们提供了一个元素叫 component 作用是:
用来动态的挂载不同的组件
实现: 使用 is 特性来进行实现的
// 点击不同的按钮, 渲染不同的组件 <div id="app"> <component :is="thisView"></component> <button @click="selected('A')">一</button> <button @click="selected('B')">二</button> <button @click="selected('C')">三</button> </div> var App = new Vue({ el: '#app', data: { thisView: 'compA' }, methods:{ selected:function(tag){ this.thisView = 'comp' + tag } }, components: { 'compA': { template: '<div > 一个和尚挑水喝</div>' }, 'compB': { template: '<div > 两个和尚抬水喝</div>' }, 'compC': { template: '<div > 三个和尚没水喝</div>' } } })
来源: http://www.jianshu.com/p/2e8ff1918bf1