可以定义共用的变量,在每个组件中使用,引入组件中之后,各个变量是相互独立的,值的修改在组件中不会相互影响。
引入组件之后与组件中的对象和方法进行合并,相当于扩展了父组件的对象与方法,可以理解为形成了一个新的组件
export const myMixins = {
components:{},
data() {
return {
age: 18,
}
},
mounted() {
this.getAge()
},
methods: {
getAge() {
console.log(this.age)
}
}
}
组件A
import { myMixins } from "@/mixins/myMixins.js";
export default {
mixins: [myMixins],
data() {
return {}
},
created() {
this.age++
},
}
组件B
export default {
mixins: [myMixins],
data() {
return {}
},
}
输出
19
18
值为对象(components、methods 、computed、data)的选项,混入组件时选项会被合并,键冲突时优先组件,组件中的键会覆盖混入对象的
// myMixins.js
export const myMixins = {
components:{},
data() {
return {
age: 18,
}
},
methods: {
getAge1() {
console.log("age1 from mixins =", this.age )
},
getAge2() {
console.log("age2 from mixins =", this.age )
},
}
}
// template.vue
import { myMixins } from "@/mixins/myMixins.js";
export default {
mixins: [myMixins],
data() {
return {
age: 20,
}
},
mounted() {
this.getAge1();
this.getAge2();
this.getAge3();
},
methods: {
getAge1() {
console.log('age1 from template =', this.age)
},
getAge3() {
console.log('age3 from template =', this.age)
},
}
}
输出
age1 from template = 20
age2 from mixins = 20
age3 from template = 20
所有混入对象的选项将被混入该组件本身的选项;
同名钩子函数将混合为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用;
methods, components 和 directives,将被混合为同一个对象。两个对象键名冲突时,取组件对象的键值对。