Keep Alive 缓存
1. 常见方法
// 组件 export default { name: 'test-keep-alive', data () { return { includedComponents: "test-keep-alive" } } }
<keep-alive include="test-keep-alive"> <!-- 将缓存name为test-keep-alive的组件 --> <component></component> </keep-alive> <keep-alive include="a,b"> <!-- 将缓存name为a或者b的组件,结合动态组件使用 --> <component :is="view"></component> </keep-alive> <!-- 使用正则表达式,需使用v-bind --> <keep-alive :include="/a|b/"> <component :is="view"></component> </keep-alive> <!-- 动态判断 --> <keep-alive :include="includedComponents"> <router-view></router-view> </keep-alive> <keep-alive exclude="test-keep-alive"> <!-- 将不缓存name为test-keep-alive的组件 --> <component></component> </keep-alive>
2. 结合router,缓存部分页面
使用$route.meta的keepAlive属性:
<keep-alive> <router-view v-if="$route.meta.keepAlive"></router-view> </keep-alive> <router-view v-if="!$route.meta.keepAlive"></router-view>
需要在router
中设置router的元信息meta:
//...router.js export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello, meta: { keepAlive: false // 不需要缓存 } }, { path: '/page1', name: 'Page1', component: Page1, meta: { keepAlive: true // 需要被缓存 } } ] })
3. B跳转到A页面A页面需要缓存,C跳转到A页面A页面不需要缓存
// A页面
{ path: '/', name: 'A', component: A, meta: { keepAlive: true // 需要被缓存 } }
// B页面
export default { data() { return {}; }, methods: {}, beforeRouteLeave(to, from, next) { // 设置下一个路由的 meta to.meta.keepAlive = true; // B 跳转到 A 时,让 A 缓存,即不刷新 next(); } };
// C页面 export default { data() { return {}; }, methods: {}, beforeRouteLeave(to, from, next) { // 设置下一个路由的 meta to.meta.keepAlive = false; // C 跳转到 A 时让 A 不缓存,即刷新 next(); } };