vue中mixins的使用方法和注意点
概念
混入 (mixins): 是一种分发 Vue 组件中可复用功能的非常灵活的方式。混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项。
用法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| export const myMixin = { data() { return { num: 1, } }, created() { this.hello(); } methods: { hello() { console.log('hello from mixin') } } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| <template> <div> 组件 </div> </template> <script> import {myMixin} from '@/assets/mixin.js'
export default{ mixins:[myMixin], } </script>
|
特点
- 方法和参数在各组件中不共享
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div> 组件1 </div> </template> <script> import {myMixin} from '@/assets/mixin.js'
export default{ mixins:[myMixin], created(){ console.log("组件1:",this.num++); } } </script>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <div> 组件2 </div> </template> <script> import {myMixin} from '@/assets/mixin.js'
export default{ mixins:[myMixin], created(){ console.log("组件2:",this.num); } } </script>
|
输出:
组件1:2
组件2:1
- 值为对象的选项,如methods,components等,选项会被合并,键冲突的组件会覆盖混入对象的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| export const myMixin = { data() { return { num: 1 } }, created() { this.hello(); }, methods: { func_one() { console.log('1'); }, func_two() { console.log('2'); } } }
export default { mixins: [myMixin], created() { this.func_three(); this.func_one(); this.func_two(); }, methods { func_three() { console.log('3'); } func_two() { console.log('4'); } } }
|
输出:
3
1
4
- 值为函数的选项,如created,mounted等,就会被合并调用,混合对象里的钩子函数在组件里的钩子函数之前调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| export const myMixin = { data() { return { num: 1, } }, created() { console.log('mixin') } }
export default { mixins: [myMixin], created() { console.log('self') }, }
|
输出:
mixin
self
与vuex的区别
- vuex:用来做状态管理的,里面定义的变量在每个组件中均可以使用和修改,在任一组件中修改此变量的值之后,其他组件中此变量的值也会随之修改。
- Mixins:可以定义共用的变量,在每个组件中使用,引入组件中之后,各个变量是相互独立的,值的修改在组件中不会相互影响。
与公共组件的区别
组件:在父组件中引入组件,相当于在父组件中给出一片独立的空间供子组件使用,然后根据props来传值,但本质上两者是相对独立的。
Mixins:则是在引入组件之后与组件中的对象和方法进行合并,相当于扩展了父组件的对象与方法,可以理解为形成了一个新的组件。
转发:https://www.jianshu.com/p/bcff647d24ec