缓存组件<keep-alive>
1.组件作用
组件, 默认会缓存内部的所有组件实例,当组件需要缓存时首先考虑使用此组件。
2.使用场景
场景1:tab切换时,对应的组件保持原状态,使用keep-alive组件
使用: KeepAlive | Vue.js,参考官网即可。
场景2:路由切换回来时如果需要保持当前路由界面下的状态,就需要使用缓存。
使用:
1.定义路由时添加字段标识 isKeepAlive,防止缓存所有路由
javascript
{"path": "/home",
"name": "home",
"component": "/home/index",
"label": "首页",
"meta": {
"icon": "home",
"title": "首页",
"isKeepAlive": false
}
}
2.使用 <router-view/>
html
<!--如果字段标识缓存,就缓存,否则不缓存-->
<!--$route表示路由信息-->
<router-view v-slot="{ Component }">
<keep-alive>
<component :is="Component" v-if="$route.meta.isKeepAlive" :key="$route.fullPath" />
</keep-alive>
<component :is="Component" v-if="!$route.meta.isKeepAlive" :key="$route.fullPath" />
</router-view>
3.可能的报错
报错内容:parentComponent.ctx.deactivate is not a function
解决: 给component添加key属性,否则在触发deactivate钩子时会出问题