16动态组件
# 动态组件
//keep-alive可以缓存组件,让组件不需要每次切换都销毁再重新渲染
//但是会让created组件失效,解决办法是使用activated激活生命周期
<button @click="toggle">按钮</button>
<keep-alive>
<component :is="com"></component>
</keep-alive>
import acom from "./components/acom.vue"
import bcom from "./components/bcom.vue"
export default {
name: 'App',
data(){
return{
com:"bcom"
}
},
components: {
acom,
bcom
},
methods:{
toggle(){
if(this.com === "acom"){
this.com = 'bcom'
}else{
this.com = 'acom'
}
}
}
}
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
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
%accordion% keep-alive可以缓存组件🚀 %accordion%
<div id="app">
<button @click="toggle">切换</button>
<keep-alive>
<component :is="myComponent"></component>
</keep-alive>
</div>
<script>
//局部组件(区域注册)子组件
let myComponent1 = {
template: "<div>👧我是子组件1</div>",
};
let myComponent2 = {
template: "<div>👦我是子组件2</div>",
};
//👨父组件
new Vue({
el: "#app",
data: {
myComponent: "myComponent1"
},
components: {
myComponent1,
myComponent2,
},
methods: {
toggle() {
if (this.myComponent === "myComponent1") {
this.myComponent = "myComponent2"
} else {
this.myComponent = "myComponent1"
}
}
},
});
</script>
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
38
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
38
编辑 (opens new window)
上次更新: 2023/08/06, 00:38:41