谈谈 mixin
是什么
- mixin(混入)本质是一个 js 对象,它可以包含组件中功能选项,如 data、components、methods、created、computed 等等
- 当组件使用 mixins 对象时,所有 mixins 对象的选项都将被混入该组件本身的选项中来。
怎么做
mixin 分为:局部混入
跟全局混入
局部混入
- 定义一个 mixin 对象,有组件 options 的 data、methods 属性
- 组件通过 mixins 属性引入 mixin 对象
var myMixin = {
created:function(){
this.hello()
},
methods:{
hello:function(){
console.log('hello from mixin!')
}
}
}
Vue.component('componentA',{
mixins: [myMixin]
})
该组件在使用的时候,混合了 mixin 里面的方法,在自动执行 created 生命钩子,执行 hello 方法
全局混入
- 通过
Vue.mixin()
进行全局的混入 - 使用全局混入需要特别注意,因为它会影响到每一个组件实例(包括第三方组件)
Vue.mixin({
created: function () {
console.log("全局混入")
}
})