mixin特点:
- 组件 data 优先级 高于 mixin 的data优先级
- 组件 methods 优先级 高于 mixin 的methods优先级
- 声明周期函数,先执行 mixin 里面的,再执行组件里面的
- 局部mixin,需要在组件中注册 mixins: [myMixin]
- 全局mixin 无需在组件中注册,自动注入。
定义局部mixin
和定义局部组件类似,支持data,methods以及声明周期函数。
mixin.js
const myMixin = {
data() {
return {
msg: 'hello vue3'
}
},
created() {
console.log('mixin created');
},
methods: {
handleClick() {
console.log('mixin', this.msg);
}
}
}
组件中使用:
组件中data,methods优先级都会高于mixin
const app = Vue.createApp({
mixins: [myMixin], // 注册mixin
template: `<div>
{{msg}}
<button @click="handleClick">点击</button>
</div>`,
created() {
console.log('app created');
},
data() {
return {
msg: 'hello world'
}
},
methods: {
handleClick() {
console.log('app', this.msg);
}
},
})
定义全局mixin(不推荐)
// 全局mixin 无需在组件中注册,自动注入。
app.mixin({
mounted() {
console.log('这是一个全局的mixin');
}
})
调整mixin中属性的优先级
const myMixin = {
msg: 'hello mixin ~'
}
// $options 组件注册的所有选项都会在 $options 中
const app = Vue.createApp({
mixins: [myMixin],
msg: 'hello app ~',
template: `
<div>
{{ $options.msg }}
</div>`,
})
// ** 调整mixin中属性(如:msg)的优先级,使mixin的优先级高级组件的
app.config.optionMergeStrategies.msg = (mixinValue, appValue) => {
return mixinValue || appValue;
}