示例
App.vue
<template>
<div>
<the-header></the-header>
<button @click="setSelectedComponent('active-goals')">Active Goals</button>
<button @click="setSelectedComponent('manage-goals')">Manage Goals</button>
<!-- <active-goals v-if="selectedComponent === 'active-goals'"></active-goals>
<manage-goals v-if="selectedComponent === 'manage-goals'"></manage-goals> -->
<!-- keep-alive means that components should not be removed and deleted from DOM when switching between components. -->
<keep-alive>
<component :is="selectedComponent"></component>
</keep-alive>
</div>
</template>
使用keep-alive包裹components,可以切换显示的时候,可以保留状态,也就是不从DOM删除。