minins与components相似,mixins选项也用于注册在外部封装好的代码,不过这些代码更加碎片化,并不如组件一样成体系,混入的目的在于灵活地分发组件中一些可复用的功能。
混入可以将一些封装好的选项混入另一个组件中,在混入过程中,如果没有发生冲突,则执行合并,如果发生冲突且用户没有指定解决策略,Vue则采用默认策略。
注意:谨慎使用全局混入,因为它会影响每个单独创建的 Vue 实例 (包括第三方组件)。
冲突选项 | 合并策略 | 冲突策略 |
---|---|---|
data | 合并根节点数据 | 优先采用组件的数据 |
mounted等钩子函数 | 混合为数组 | 全部调用且优先调用mixins的钩子函数 |
methods/components/directives等 | 混合为同一对象 | 优先采用组件的键值对 |
watch | 混合为数组 | 全部调用且优先调用mixins的watch |
以下为代码:
组件:
<template>
<div>
<p>computed: {{name}}</p>
<p>watch: {{secondName}}</p>
<button @click="changeName">点击</button>
</div>
</template>
<script>
import HelloWorld from '../components/HelloWorld';
export default {
data() {
return {
firstName: 'Home',
secondName: '组件'
};
},
mixins: [HelloWorld],
computed: {
name() {
return this.firstName + '组件computed';
}
},
watch: {
firstName() {
this.secondName = '组件watch';
console.log('组件watch')
}
},
mounted() {
console.log('组件mounted');
},
methods:{
changeName(){
this.firstName = '组件 methods +'
console.log('组件 methods')
}
}
};
</script>
混入组件:
<template>
<div>
<p>混入组件</p>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data() {
return {
firstName: 'HelloWorld',
secondName: '混入'
};
},
computed: {
name() {
return this.firstName + '混入computed';
}
},
watch: {
firstName() {
this.secondName = '混入watch';
console.log('混入watch')
}
},
mounted() {
console.log('混入mounted');
},
methods: {
changeName() {
this.firstName = '混入 methods +';
console.log('混入 methods');
}
}
};
</script>
结果: