当使用 来在多个组件间作切换时,被切换掉的组件会被卸载。我们可以通过组件强制被切换掉的组件仍然保持“存活”的状态。
组件切换
<button @click=“changeComponentHandle”>切换
在大型项目中,我们可能需要拆分应用为更小的块,并仅在需要时再从服务器加载相关组件。Vue 提供了 defineAsyncComponent方法来实现此功能
<template><h3>组件切换</h3><keep-alive><component :is="currentTab"></component></keep-alive><button @click="changeComponentHandle">切换</button>
</template>
<script>
import { defineAsyncComponent } from 'vue'
import ComponentA from "./components/ComponentA.vue"
const AsyncComponentB = defineAsyncComponent(() =>import('./components/ComponentB.vue')
)
export default {components: {ComponentA,AsyncComponentB},data() {return {currentTab: "ComponentA",}},methods: {changeComponentHandle() {this.currentTab = this.currentTab == "ComponentA" ? "AsyncComponentB" : "ComponentA"}}
}
</script>