Vue 2 中的 Mixins 模式
在 Vue 2 里,mixins
是一种灵活的复用代码的方式,它能让你在多个组件间共享代码。借助 mixins
,你可以把一些通用的选项(像 data
、methods
、computed
等)封装到一个对象里,然后在多个组件中使用。
下面是 mixins
的基本使用示例:
// 定义一个 mixin
const myMixin = {
data() {
return {
mixinData: '这是 mixin 中的数据'
}
},
methods: {
mixinMethod() {
console.log('这是 mixin 中的方法');
}
}
};
// 定义一个组件并使用 mixin
const MyComponent = {
mixins: [myMixin],
data() {
return {
componentData: '这是组件中的数据'
}
},
methods: {
componentMethod() {
console.log('这是组件中的方法');
}
}
};
在这个例子中,MyComponent
组件使用了 myMixin
,这意味着 MyComponent
能够访问 myMixin
里定义的 data
和 methods
。
选项合并规则
当组件使用 mixins
时,若组件和 mixin
存在同名选项,就需要依据一定规则进行合并:
数据对象(data
)
如果组件和 mixin
都定义了 data
选项,它们会递归合并。当出现键名冲突时,组件的数据会覆盖 mixin
的数据。
const myMixin = {
data() {
return {
message: 'mixin 消息'
}
}
};
const MyComponent = {
mixins: [myMixin],
data() {
return {
message: '组件消息'
}
}
};
// 创建组件实例
const vm = new Vue(MyComponent);
console.log(vm.message); // 输出: 组件消息
钩子函数
如果组件和 mixin
都定义了相同的钩子函数(如 created
、mounted
等),这些钩子函数会被合并成一个数组,并且都会被调用。mixin
的钩子函数会先于组件的钩子函数执行。
const myMixin = {
created() {
console.log('mixin 的 created 钩子');
}
};
const MyComponent = {
mixins: [myMixin],
created() {
console.log('组件的 created 钩子');
}
};
// 创建组件实例
const vm = new Vue(MyComponent);
// 输出:
// mixin 的 created 钩子
// 组件的 created 钩子
方法、计算属性和 watch
如果组件和 mixin
存在同名的方法、计算属性或 watch
,组件的定义会覆盖 mixin
的定义。
结合你提供的代码,MapBaseMarker.js
组件混入了 MapBaseMixin.js
,两个文件里都有 init
方法。当 MapBaseMarker
组件实例化时,调用的 init
方法是 MapBaseMarker.js
文件里定义的 init
方法,而非 MapBaseMixin.js
里的 init
方法。
// MapBaseMixin.js
const MapBaseMixin = {
methods: {
init() {
console.log('MapBaseMixin 中的 init 方法');
}
}
};
// MapBaseMarker.js
export default {
mixins: [MapBaseMixin],
methods: {
init() {
console.log('MapBaseMarker 中的 init 方法');
}
}
};
// 当创建 MapBaseMarker 组件实例时,调用的 init 方法是 MapBaseMarker 中的 init 方法
综上所述,当组件和 mixin
存在同名方法时,组件自身的方法会覆盖 mixin
里的同名方法。