前端流行框架Vue3教程:25. 组件保持存活
25. 组件保持存活
当使用<component :is="...">
来在多个组件间作切换时,被切换掉的组件会被卸载。
我们可以通过 <keep-allve>
组件强制被切换掉的组件仍然保持"存活”的状态
我们先来看个例子(依然用上节课的代码改动下):
ComponentA.vue
<script>
export default {beforeUnmount() {console.log('组件销毁之前')},unmounted() {console.log('组件销毁完毕')}
};
</script><template><h3>ComponentA</h3>
</template>
我们点击按钮,就会看到:
说明组件被卸载了。我们写点明文演示下:
<script>
export default {data() {return {message: "老数据"};},beforeUnmount() {console.log('组件销毁之前')},unmounted() {console.log('组件销毁完毕')}, methods: {updateHandle() {this.message = "新数据";}}
};
</script><template><h3>ComponentA</h3><p>{{ message }}</p><button @click="updateHandle">更新数据</button>
</template>
我们点更新数据,A组件会变成新数据。切换组件B后,再去切回A组件,发现又变成了老数据。说明我们在切换的时候,组件被卸载了,所以加载的还是原始的数据。
那么我们怎么保持组件存活呢?(保持新数据不变)
App.vue
<script>
...
</script>
<template><!-- 使用 keep-alive 组件来缓存动态组件,避免重复渲染 --><keep-alive><component :is="tabComponent"></component></keep-alive><button @click="changeHandle">切换组件</button>
</template>
此时,我们切换回A组件,就还是新数据了