mixins基础概况
vue中的解释是这样的,如果觉得语言枯燥的可以自行跳过嘿~
混入 (mixins): 是一种分发 Vue 组件中可复用功能的非常灵活的方式。混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被混入该组件本身的选项。
怎么用?
举个栗子:
定义一个混入对象

把混入对象混入到当前的组件中

用法似不似相当简单呀
mixins的特点
1 方法和参数在各组件中不共享
混合对象中的参数num

组件1中的参数num进行+1的操作

组件2中的参数num未进行操作

看两组件中分别输出的num值


大家可以看到,我在组件1里改变了num里面的值,组件2中的num值还是混入对象里的初始值
2 值为对象的选项,如methods,components等,选项会被合并,键冲突的组件会覆盖混入对象的
混入对象中的方法

组件中的方法

打印台的输出

3 值为函数的选项,如created,mounted等,就会被合并调用,混合对象里的钩子函数在组件里的钩子函数之前调用
混入对象函数中的console

组件函数中的console

打印台的打印

与vuex的区别
经过上面的例子之后,他们之间的区别应该很明显了哈~
vuex:用来做状态管理的,里面定义的变量在每个组件中均可以使用和修改,在任一组件中修改此变量的值之后,其他组件中此变量的值也会随之修改。
Mixins:可以定义共用的变量,在每个组件中使用,引入组件中之后,各个变量是相互独立的,值的修改在组件中不会相互影响。
与公共组件的区别
同样明显的区别来再列一遍哈~
组件:在父组件中引入组件,相当于在父组件中给出一片独立的空间供子组件使用,然后根据props来传值,但本质上两者是相对独立的。
Mixins:则是在引入组件之后与组件中的对象和方法进行合并,相当于扩展了父组件的对象与方法,可以理解为形成了一个新的组件。
网友评论