keep-alive
避免多次重复渲染降低性能。可以进行组件缓存,维持当前的状态。
应用场景
- 商品列表页点击商品跳转到商品详情,返回后仍显示原有信息
- 订单列表跳转到订单详情,返回,等等场景。
keep-alive声明周期
- 初次进入时:created > mounted > activated;退出后触发 deactivated
- 再次进入:会触发 activated;事件挂载的方法等,只执行一次的放在 mounted 中;组件每次进去执行的方法放在 activated 中
项目实践一、
1. App.vue的更改
<div id="app" class='wrapper'>
<keep-alive>
<!-- 需要缓存的视图组件 -->
<router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<!-- 不需要缓存的视图组件 -->
<router-view v-if="!$route.meta.keepAlive"></router-view>
</div>
2. 路由中的配置
{
path: 'list',
name: 'itemList', // 商品管理
component: () =>
import("@/views/item/list"),
},
meta: {
keepAlive: true,
title: '商品管理'
}
}
3. beforeRouteLeave
beforeRouteLeave(to, from, next) {
if(to.path == '缓存页的详情页') {
if(!from.meta.keepAlive){
from.meta.keepAlive = true;
}
} else {
from.meta.keepAlive = false;
}
next();
},
注意:这种方法有个坑,虽然实现了缓存的功能,但是这个方法keepAlive一旦被创建,就不会被销毁,如果想通过改变meta的方式来销毁keepAlive是不可能的。
如果你设置了keepAlive之后,又有某种特殊情况想销毁的话,可以通过vuex配合设置include来决定页面是否需要keepAlive
项目实践二、
1.需要设置缓存的页面
<keep-alive
:include="$store.getters.include"
:exclude="$store.getters.exclude"
>
<router-view />
</keep-alive>
getters中
const getters = {
include: (state) => state.cache.include,
exclude: (state) => state.cache.exclude,
}
export default getters
cache文件中
const state = {
include: "danger",
exclude: "",
};
const mutations = {
SET_INCLUDE: (state, data) => {
state.include = data;
},
SET_EXCLUDE: (state, data) => {
state.exclude = data;
},
};
const actions = {
setinclude({ commit }, include) {
commit("SET_INCLUDE", include);
},
setexclude({ commit }, exclude) {
commit("SET_EXCLUDE", "");
commit("SET_EXCLUDE", exclude);
},
};
export default {
namespaced: true,
state,
mutations,
actions,
};
2. 需求
B页面跳转到A,A页面需要缓存
C页面跳转到A,A页面不需要被缓存
created() {
this.$store.dispatch("cache/setexclude", "");
},
beforeRouteLeave(to, from, next) {
if (to.path == "/danger/self/selfForm") {
this.$store.dispatch("cache/setexclude", "");
} else {
console.log(to);
this.$store.dispatch("cache/setexclude", "");
this.$store.dispatch("cache/setexclude", "danger");
}
next();
},
注意: 多层嵌套
嵌套<router-view></router-view>,但凡有超过两个以上的router-view且是父子级关系,请都加上keep-alive,只加一个不会生效.
// app.vue
<keep-alive include="app,index">
<router-view></router-view>
</keep-alive>
// other.vue
<keep-alive include="app,index">
<router-view></router-view>
</keep-alive>
可能有不足的地方,请各位大佬评论区留言