定义一个mixin对象
const mymixin = {
data(){
return {
count:2,
number:666,
childs:12
}
},
created(){
console.log('mixin created');
},
methods:{
mixinclick(){
console.log('mixin click');
}
},
}
const app = Vue.createApp({
data(){
return{
count:1
}
},
mixins:[mymixin],
created(){
console.log('created');
},
template:`
<div @click="mixinclick">
{{count}}
{{number}}
<child/>
</div>
`
})
app.component('child',{
mixins:[mymixin],
template:`<div>{{childs}}</div>`
})
app.mount('#root');
全局mixin
const app = Vue.createApp({
data(){
return{
count:1
}
},
//mixins:[mymixin],
created(){
console.log('created');
},
template:`
<div @click="mixinclick">
{{count}}
{{number}}
<child/>
</div>
`
})
app.component('child',{
//mixins:[mymixin],
template:`<div>{{childs}}</div>`
})
app.mixin({
data(){
return {
count:2,
number:666,
childs:12
}
},
created(){
console.log('mixin created');
},
methods:{
mixinclick(){
console.log('mixin click');
}
},
})
app.mount('#root');
自定义属性
自定义的属性,组件中的优先级高于mixin属性优先级
vue中位定义的属性会保存在 options中,可以通过 this.$options.
访问
const mymixin = {
data(){
return {
count:2,
number:666,
childs:12
}
},
created(){
console.log('mixin created');
},
methods:{
mixinclick(){
console.log('mixin click');
}
},
}
const app = Vue.createApp({
mixins:[mymixin],
number:11,
created(){
console.log('created');
},
template:`
<div @click="mixinclick">
{{count}}
<div>{{this.$options.number}}</div>
<child/>
</div>
`
})
app.component('child',{
mixins:[mymixin],
template:`<div>{{childs}}</div>`
})
app.mount('#root');
更改自定义属性优先级
app.config.optionMergeStrategies.number = (mixinValue,appValue) =>{
return mixinValue || appValue;
}
const mymixin = {
number:666,
data(){
return {
count:2,
childs:12
}
},
created(){
console.log('mixin created');
},
methods:{
mixinclick(){
console.log('mixin click');
}
},
}
const app = Vue.createApp({
mixins:[mymixin],
number:1111111111111,
created(){
console.log('created');
},
template:`
<div @click="mixinclick">
{{count}}
<div>{{this.$options.number}}</div>
<child/>
</div>
`
})
app.component('child',{
mixins:[mymixin],
template:`<div>{{childs}}</div>`
})
app.config.optionMergeStrategies.number = (mixinValue,appValue) =>{
return mixinValue || appValue;
}
app.mount('#root');