vue中对mixins的理解和使用的介绍 超、凢脫俗 2022-11-29 11:48 138阅读 0赞 ### mixins ### vue中提供了一种混合机制–mixins(混合),用来更高效的实现组件内容的复用。 mixins是一种分发 Vue 组件中可复用功能的非常灵活的方式。混合对象可以包含任意组件选项。当组件使用混合对象时,所有混合对象的选项将被混入该组件本身的选项。 ### mixins理解 ### 组件在引用之后相当于在父组件内开辟了一块单独的空间,来根据父组件props过来的值进行相应的操作,单本质上两者还是泾渭分明,相对独立。 而mixins则是在引入组件之后,则是将组件内部的内容如data等方法、method等属性与父组件相应内容进行合并。相当于在引入后,父组件的各种属性方法都被扩充了。 ###### 组件引用: ###### 父组件 + 子组件 >>> 父组件 + 子组件 ###### mixins: ###### 父组件 + 子组件 >>> new父组件 有点像注册了一个vue的公共方法,可以绑定在多个组件或者多个Vue对象实例中使用。另一点,类似于在原型对象中注册方法,实例对象即组件或者Vue实例对象中,仍然可以定义相同函数名的方法进行覆盖,有点像子类和父类的感觉。 ### mixins的使用 ### 父组件html <div id="app"> <child></child> <kid></kid> </div> 子组件 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,则变得十分简单: 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中的方法会被覆盖。 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" 3、合并生命周期此时,若单击h1标签,则在控制台中打印"Child foo() 1" ### 合并生命周期 ### 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有了比较深入的了解,在设计复杂组件时是很有必要的。
还没有评论,来说两句吧...