动态切换组件导致的问题
动态切换组件使得每次组件都会被卸载然后重新初始化,导致数据每次都初始化,无法保存前一个组件的数据.
ComponentA.vue
<template>
<h3>ComponentA</h3>
<p>状态:{{ message }}</p>
<button @click="changeStatus">开关切换</button>
</template>
<script>
export default {
data() {
return {
message: "关闭",
};
},
methods: {
changeStatus() {
this.message = this.message == "关闭" ? "开启" : "关闭";
},
},
beforeUnmount() {
console.log("组件卸载之前");
},
unmounted() {
console.log("组件卸载之后");
},
};
</script>
引入keeplive标签
keeplive标签包裹component 标签,使得存活不会被销毁
初始状态关闭
开关切换变成了开启
两次切换组件后回到了A发现还是开启的而不是默认的关闭
app.vue
<template>
<KeepAlive>
<component :is="choseComponent"></component>
</KeepAlive>
<button @click="changeComponent">切换组件</button>
</template>
<script>
import ComponentA from "./components/ComponentA.vue";
import ComponentB from "./components/ComponentB.vue";
export default {
data() {
return {
choseComponent: "ComponentA",
};
},
components: {
ComponentA,
ComponentB,
},
methods: {
changeComponent() {
console.log(this.choseComponent);
this.choseComponent =
this.choseComponent == "ComponentA" ? "ComponentB" : "ComponentA";
},
},
};
</script>
componentA.vue
<template>
<h3>ComponentA</h3>
<p>状态:{{ message }}</p>
<button @click="changeStatus">开关切换</button>
</template>
<script>
export default {
data() {
return {
message: "关闭",
};
},
methods: {
changeStatus() {
this.message = this.message == "关闭" ? "开启" : "关闭";
},
},
beforeUnmount() {
console.log("组件卸载之前");
},
unmounted() {
console.log("组件卸载之后");
},
};
</script>
总结
大家喜欢的话,给个👍,点个关注!给大家分享更多计算机专业学生的求学之路!
版权声明:
发现你走远了@mzh原创作品,转载必须标注原文链接
Copyright 2024 mzh
Crated:2024-3-1