vue3基础-mixin使用
vue3-mixin使用
·
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;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐

所有评论(0)