Skip to main content

谈谈 mixin

是什么

  1. mixin(混入)本质是一个 js 对象,它可以包含组件中功能选项,如 data、components、methods、created、computed 等等
  2. 当组件使用 mixins 对象时,所有 mixins 对象的选项都将被混入该组件本身的选项中来。

怎么做

mixin 分为:局部混入全局混入

局部混入

  1. 定义一个 mixin 对象,有组件 options 的 data、methods 属性
  2. 组件通过 mixins 属性引入 mixin 对象
var myMixin = {
created:function(){
this.hello()
},
methods:{
hello:function(){
console.log('hello from mixin!')
}
}
}
Vue.component('componentA',{
mixins: [myMixin]
})

该组件在使用的时候,混合了 mixin 里面的方法,在自动执行 created 生命钩子,执行 hello 方法

全局混入

  1. 通过 Vue.mixin() 进行全局的混入
  2. 使用全局混入需要特别注意,因为它会影响到每一个组件实例(包括第三方组件)
Vue.mixin({
created: function () {
console.log("全局混入")
}
})