1. 代码
1.1 App.vue
<template>
<div id="app">
根组件
<hr />
<button @click="comName = 'Left'">展示Left组件</button>
<button @click="comName = 'Right'">展示Right组件</button>
<div class="box">
<!-- <keep-alive include="Left,Right">
<component :is="comName"></component>
</keep-alive> -->
<keep-alive exclude="Left">
<component :is="comName"></component>
</keep-alive>
</div>
<router-view />
</div>
</template>
<script>
import Left from "@/components/Left.vue";
import Right from "@/components/Right.vue";
export default {
components: {
Left,
Right,
},
data() {
return {
comName: "",
};
},
};
</script>
<style lang="less">
#app {
width: 100%;
height: 200px;
background-color: skyblue;
}
</style>
1.2 Left.vue
<template>
<div id="left">
<h3>Left 组件</h3>
<slot name="default"></slot>
</div>
</template>
<script>
export default {
name: 'Left',
data() {
return {};
},
created() {
console.log('Left组件被创建!');
},
activated() {
console.log("Left组件被激活了,activated");
},
deactivated() {
console.log("Left组件被缓存了,deactivated");
},
};
</script>
<style lang="less" scoped>
#left {
background-color: pink;
height: 150px;
width: 100%;
}
</style>
1.3 Right.vue
<template>
<div id="Right">
<h3>这是Right组件</h3>
</div>
</template>
<script>
export default {
name: "Right",
data() {
return {};
},
methods: {},
created() {
console.log('Right组件被创建!');
},
activated() {
console.log('Right组件被激活了,activated');
},
deactivated() {
console.log('Right组件被缓存了,deactivated');
}
};
</script>
<style>
#Right {
background-color: greenyellow;
height: 150px;
width: 100%;
}
</style>
1.4 结果
-
点击“展示Left组件”,显示如下:
-
点击“展示Right组件”,显示如下:
-
如果使用的是keep-alive的exclude属性,不断切换组件,控制台打印如下:
因为设置的Left组件不被缓存,所以每次切换到Left组件就要重新创建Left组件。 -
如果使用的是keep-alive的include属性,不断切换组件,控制台打印如下:
2. 相关的知识点
2.1 activated、deactivated生命周期函数
- 当组件第一次被创建的时候,既会执行 created 生命周期,也会执行 activated 生命周期;
- 但是,当组件被激活的时候,只会触发 activated 生命周期,不再触发created。因为组件没有被重新创建。
2.2 动态组件
- component 标签是 vue 内置的,作用:组件的占位符。
- is 属性的值,表示渲染的组件的名字;
- is 属性的值, 应该是组件在components节点下的注册名称;
- keep-alive 可以把内部的组件进行缓存,而不是销毁组件。
- 在使用 keep-alive 的时候,可以通过 inculde 指定哪些组件需要被缓存;也可以使用 exclude属性指定哪些组件不需要被缓存。
- 不要同时使用 include 和 exclude 这两个属性。
参考: 黑马vue视频。