mixins
混合 (mixins) 是一种分发 Vue 组件中可复用功能的非常灵活的方式。
相当于扩充父组件的属性、方法等,类似于在原型对象中注册方法。
如果在引用mixins的同时,在组件中重复定义相同的方法,则mixins中的方法会被覆盖
<div id="app">
<child></child>
<kid></kid>
</div>
//不用minins,同样的方法要定义两次
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++)
}
}
})
//用minins,抽取公用的方法和属性,实现了功能的复用
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]
})

浙公网安备 33010602011771号