一、基础用法
// 定义一个混合对象
var myMixin = {
created: function () {
this.hello()
},
methods: {
hello: function () {
console.log('hello from mixin!')
}
}
}
// 定义一个使用混合对象的组件
var Component = Vue.extend({
mixins: [myMixin]
})
var component = new Component() // -> "hello from mixin!"
复制代码
二、选项合并
当组件和混入对象mixins含有同名选项时:
1、数据对象同名———在内部会进行浅合并,在和组件的数据发生冲突时,以组件数据优先。
var mixin = {
data: function () {
return {
message: 'hello',
foo: 'abc'
}
}
}
new Vue({
mixins: [mixin],
data: function () {
return {
message: 'goodbye',
bar: 'def'
}
},
created: function () {
console.log(this.$data)
//这里的message字段同名,以该组件中为准
// => { message: "goodbye", foo: "abc", bar: "def" }
}
})
复制代码
2、钩子函数同名———同名钩子函数将混合为一个数组,因此都将被调用,混入对象mixins的钩子将在组件自身钩子之前调用。
var mixin = {
created: function () {
console.log('混入对象的钩子被调用')
}
}
new Vue({
mixins: [mixin],
created: function () {
console.log('组件钩子被调用')
}
})
// => "混入对象的钩子被调用"
// => "组件钩子被调用"
复制代码
3、值为对象的选项———例如在methods, components 和 directives 中,将被混合为同一个对象。两个对象键名冲突时,取组件对象的键值对。
var mixin = {
methods: {
foo: function () {
console.log('foo')
},
conflicting: function () {
console.log('from mixin')
}
}
}
var vm = new Vue({
mixins: [mixin],
methods: {
bar: function () {
console.log('bar')
},
conflicting: function () {
console.log('from self')
}
}
})
vm.foo() // => "foo"
vm.bar() // => “bar"
//这里的conflicting方法同名,以该组件为准
vm.conflicting() // => "from self"
复制代码
三、全局混入
也可以全局注册混入对象。注意使用! 一旦使用全局混入对象,将会影响到 所有 之后创建的 Vue 实例。使用恰当时,可以为自定义对象注入处理逻辑。
var mixin = {
created: function() {
//获取自定义选项
let option = this.$options.doNotInit
if (!option) {
this.init();
}
},
methods: {
init (){
// 一些初始化操作
}
}
}
new Vue({
mixins: [mixin],
doNotInit: true, //自定义的选项
created: function () {
console.log('组件钩子被调用')
},
beforeRouteEnter(to, from, next) {
next(vm => {
vm.init();
})
}
})
复制代码