先来介绍一下 Mixin
1、Mixin
Mixin 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能
一个 mixin 对象可以包含任意组件选项
当组件使用 mixin 对象时,所有 mixin 对象的选项将被 混合 进入该组件本身的选项
// define a mixin object
const myMixin = {
created() {
this.hello()
},
methods: {
hello() {
console.log('hello from mixin!')
}
}
}
// define an app that uses this mixin
const app = Vue.createApp({
mixins: [myMixin]
})
app.mount('#mixins-basic') // => "hello from mixin!"
1.1 合并规则
data 函数
钩子函数
值为对象的选项,例如 methods、components
1.2 全局 mixin
一旦使用全局 mixin,它将影响每一个之后创建的组件
const app = Vue.createApp({
myOption: 'hello!'
})
// 为自定义的选项 'myOption' 注入一个处理器
app.mixin({
created() {
const myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
app.mount('#mixins-global') // => "hello!"
和 mixin 有