vue中提供了一种混合机制--mixins,用来更高效的实现组件内容的复用。最开始我一度认为这个和组件好像没啥区别。。后来发现错了。下面咱们来看看mixins和普通状况下引入组件有什么区别?javascript
混合 (mixins) 是一种分发 Vue 组件中可复用功能的很是灵活的方式。
混合对象能够包含任意组件选项。
当组件使用混合对象时,全部混合对象的选项将被混入该组件自己的选项。html
组件在引用以后至关于在父组件内开辟了一块单独的空间,来根据父组件props过来的值进行相应的操做,单本质上二者仍是泾渭分明,相对独立。vue
而mixins则是在引入组件以后,则是将组件内部的内容如data等方法、method等属性与父组件相应内容进行合并。至关于在引入后,父组件的各类属性方法都被扩充了。java
htmlapp
<div id="app"> <child></child> <kid></kid> </div>
js函数
Vue.component('child',{ template:`<h1 @click="foo">child component</h1>`, methods:{ foo(){ console.log('Child foo()'+this.msg++) } } }) Vue.component('kid',{ template:`<h1 @click="foo">kid component</h1>`, methods:{ foo(){ console.log('Kid foo()'+this.msg++) } } })
在借助mixins以前,在两个不一样的组件的组件中调用foo方法,须要重复定义,假若方法比较复杂,代码将更加冗余。若借助mixins,则变得十分简单:this
let mixin={ data(){ return{ msg:1 } }, methods:{ foo(){ console.log('hello from mixin!----'+this.msg++) } } } var child=Vue.component('child',{ template:`<h1 @click="foo">child component</h1>`, mixins:[mixin] }) Vue.component('kid',{ template:`<h1 @click="foo">kid component</h1>`, mixins:[mixin] })
虽然此处,两个组件用能够经过this.msg引用mixins中定义的msg,可是,小编尝试过,两个组件引用的并非同一个msg,而是各自建立了一个新的msg。若是在组件中定义相同的data,则此处会引用组件中的msg,而非mixins中的。设计
若是在引用mixins的同时,在组件中重复定义相同的方法,则mixins中的方法会被覆盖。code
var child=Vue.component('child',{ template:`<h1 @click="foo">child component</h1>`, mixins:[mixin], methods:{ foo(){ console.log('Child foo()'+this.msg++) } } })
此时,若单击h1标签,则在控制台中打印"Child foo() 1" 三、合并生命周期此时,若单击h1标签,则在控制台中打印"Child foo() 1"component
let mixin={ mounted(){ console.log('mixin say hi')//先输出 }, data(){ return{ msg:1 } }, methods:{ foo(){ console.log('mixin foo()'+this.msg++) } } } let vm=new Vue({ el:"#app", data:{ msg: 2 }, mounted: function(){ console.log('app say hi')//后输出 }, methods:{ foo(){ console.log('Parent foo()'+this.msg) } } })
经过上面的介绍,如今对mixins有了比较深刻的了解,在设计复杂组件时是颇有必要的。