1. 在 store.js 中设置全局的 数据存储字段
js
复制代码
// 是否缓存
keepAlivePage: [],
mutations :
CHANGE_KEEP_ALIVE(state, data) {
state.keepAlivePage = data
},
actions: {//类似 mothods,异步
// 页面缓存
setKeepAlivePage({
commit
}, data) {
commit("CHANGE_KEEP_ALIVE", data)
},
}
2.在 自定义的 set.js 中设置全局方法
js
复制代码
import moment from 'moment'
export default {
install(Vue) {
// 增加缓存页面
Vue.prototype.addKeepAlive = function (componentName) {
let alivePage = this.$store.state.keepAlivePage.slice(0)
alivePage.push(componentName)
alivePage = Array.from(new Set(alivePage))
this.$store.dispatch('setKeepAlivePage', alivePage)
console.log(this.$store.state.keepAlivePage, "当前缓存的页面1")
}
// 删除缓存页面
Vue.prototype.deleteKeepAlive = function (componentName) {
let alivePage = this.$store.state.keepAlivePage.slice(0)
alivePage.forEach((item, index) => {
if (item == componentName) {
alivePage.splice(index, 1)
}
})
alivePage = Array.from(new Set(alivePage))
this.$store.dispatch('setKeepAlivePage', alivePage)
console.log(this.$store.state.keepAlivePage, "当前缓存的页面2")
}
}
}
3.在 App.vue 中设置缓存
js
复制代码
<keep-alive :include="keepAlivePage">
<router-view></router-view>
</keep-alive>
computed: {
...mapState(["keepAlivePage"]),
},
4. 在页面中使用
js
复制代码
beforeRouteLeave(to, from, next) {
const _this = this;
console.log(to.name, from.name, "beforeRouteLeave")
// 如果跳转到详情页面走缓存
if (
to.name == "productetails"
) {
_this.addKeepAlive(from.name);
} else {
_this.deleteKeepAlive(from.name);
}
next()
},
或者
beforeRouteLeave(to, from, next) {
const _this = this;
// console.log(to.name, from.name, "beforeRouteLeave")
// console.log(_this.$options.name, "beforeRouteLeave")
// 如果跳转到详情页面走缓存
if (
to.name == "upcomplaintDetail" ||
to.name == "storeexamine" ||
to.name == "dealerexamine" ||
to.name == "sbuexamine" ||
to.name == "masterexamine"
) {
_this.addKeepAlive(_this.$options.name);
} else {
_this.deleteKeepAlive(_this.$options.name);
}
next()
},