一、组件保持存活
1、需求描述
点击按钮跳转到其他组件后,原组件不会被销毁
2、知识整理
1)组件生命周期
创建期:beforeCreate、created
挂载期:beforeMount、mounted
更新期:beforeUpdate、updated
销毁期:beforeUnmount、unmounted
2)保持组件存活keep-alive
<keep-alive>
<component :is="tabComponent"></component>
</keep-alive>
3)实现异步组件加载
defineAsyncComponent
3、代码演示
1)文件
2)App.vue文件
<template>
<keep-alive>
<component :is="tabComponent"></component>
</keep-alive>
<button @click="changeHandle">切换按钮</button>
</template>
<script>
import ComponentA from "./components/ComponentA.vue";
import ComponentB from "./components/ComponentB.vue";
export default{
data(){
return{
tabComponent:"ComponentA"
}
},
components: {
ComponentA,
ComponentB
},
methods:{
changeHandle(){
this.tabComponent=this.tabComponent=="ComponentA"?"ComponentB":"ComponentA"
}
}
}
</script>
3)ComponentA.vue文件
<template>
<h3>ComponentA</h3>
<p>{{ message }}</p>
<button @click="updateHandle">更新数据</button>
</template>
<script>
export default{
data(){
return {
message:"老数据"
}
},
beforeUnmount(){
console.log("组件卸载之前");
},
unmounted(){
console.log("组件卸载之后");
},
methods:{
updateHandle(){
this.message="新数据"
}
}
}
</script>
4)ComponentB.vue文件
<template>
<h3>ComponentB</h3>
</template>
<script>
</script>
5、效果展示
1)打开浏览器
2)点击“更新数据”按钮,“老数据”将变为“新数据”
3)点击“切换按钮”,跳转到组件B中
4)再点击“切换按钮”,跳转回组件A,仍保持显示“新数据”
>>>
二、 异步加载组件
1、关键代码 App.vue文件
<script>
import ComponentA from "./components/ComponentA.vue";
//import ComponentB from "./components/ComponentB.vue";
//异步加载B组件
import { defineAsyncComponent } from "vue";
const ComponentB=defineAsyncComponent(()=>import("./components/ComponentB.vue"))
2、效果展示
1)登录浏览器 ,B组件未被加载
2)点击切换按钮后,才加载B组件
>
三、学习链接
https://www.bilibili.com/video/BV1Rs4y127j8?p=37&spm_id_from=pageDriver&vd_source=841fee104972680a6cac4dbdbf144b50