keep-alive使用
需求描述:表格页跳转 新增编辑查看页面 返回需要保持表格页数据状态 并确保数据动态更新(即编辑的数据要在缓存页更新 未重新编辑提交的 保持状态不变) 实现思路:使用vuex保存 缓存列表 在合适的位置设置缓存和删除缓存即可 部分代码: 1丶需要缓存的页面
export default {
name: "staffManagement",
beforeRouteLeave(to, from, next) {
// console.log(to.name, "去哪里他");
if (to.name === "新增" || to.name == "编辑" || to.name == "查看") {
console.log("执行1");
this.$store.commit("keepAlive/iskeepAlive", "staffManagement");
} else if (to.name == "首页") {
console.log("执行2");
this.$store.commit("keepAlive/noKeepAlive", "staffManagement");
}
next();
},
复制代码
2丶设置缓存的页面 监听 设置include的动态数组
<template>
<section class="app-main">
<transition name="fade-transform" mode="out-in">
<keep-alive :include="cached">
<router-view :key="key" />
</keep-alive>
</transition>
</section>
</template>
<script>
export default {
name: "AppMain",
data() {
return {
cached: this.$store.state.keepAlive.catchArr,
};
},
watch: {
$route: {
//监听路由变化
handler: function (to, from) {
// console.log(to, from, "是什么");
if (to.name == "员工管理") {
// this.$store.commit("keepAlive/iskeepAlive", "staffManagement");
this.cached = this.$store.state.keepAlive.catchArr;
}
console.log(this.cached, "缓存列表");
},
},
},
复制代码
3丶vuex设置
const state = {
catchArr: [], //保存缓存的列表(D是固定要缓存的组件)
};
const mutations = {
// 对指定组件进行动态更改缓存(缓存)--组件调用该方法时,判断该组件是否存在于该缓存数组,无则添加
iskeepAlive: (state, component) => {
!state.catchArr.includes(component) && state.catchArr.push(component);
},
// 对指定组件进行动态更改缓存(不缓存)--组件调用该方法时,从缓存数组中删除对应的组件元素
noKeepAlive: (state, component) => {
// console.log(state, "你妈的");
let index = state.catchArr.indexOf(component);
index > -1 && state.catchArr.splice(index, 1);
},
};
export default {
namespaced: true,
state,
mutations,
};
复制代码
4丶新增 编辑 页返回时 动态刷新数据 使用actived
/* keepalive 缓存组件 生命周期执行顺序为 页面第一次进入,钩子的触发顺序created-> mounted-> activated,
退出时触发deactivated。当再次进入(前进或者后退)时,只触发activated onLoad为页面数据初始加载函数*/
mounted() {
this.onLoad();
},
activated() {
// 在首次挂载、
// 以及每次从缓存中被重新插入的时候调用
this.onLoad();
},