vue2中混入和组件递归

混入

有的时候,许多组件有着类似的功能,这些功能代码分散在组件不同的配置中。

混入和组件递归-示意图

于是,我们可以把这些配置代码抽离出来,利用混入融合到组件中。

混入和组件递归-代码抽离

具体的做法非常简单:

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
// 抽离的公共代码
const common = {
data(){
return {
a: 1,
b: 2
}
},
created(){
console.log("common created");
},
computed:{
sum(){
return this.a + this.b;
}
}
}

/**
* 使用comp1,将会得到:
* common created
* comp1 created 1 2 3
*/
const comp1 = {
mixins: [common] // 之所以是数组,是因为可以混入多个配置代码
created(){
console.log("comp1 created", this.a, this.b, this.sum);
}
}

官网

组件递归

递归:在组件内部使用自己
可以使用name来配置组件的名字,配置完成就可以使用了