想要实现前进更新后退销毁,核心在操作keep-alive的include。
具体做法就是当进入新页面时将页面name保存,再次进入就将它之后的name删除。
正常情况下页面是线性前进的:
A->B->C->D
include数组数据[A,B,C,D]
当再次进入C,就认为是D返回C
include数组数据[A,B,C]
D页面就被销毁了,从而实现了后退销毁
const keep = { namespaced: true, state: () => { return { include: [], } }, getters: { include(state) { return state.include }, }, mutations: { add(state, name) { let b = false let i = 0 for (; i < state.include.length; ++i) { let e = state.include[i] if (e == name) { b = true break } } if (!b) { state.include.push(name) } else { state.include.splice(i + 1) } } }, actions: { } } export default keep
import store from "../store" router.beforeEach((to, from,next) => { // 页面name要和route 的name一样 store.commit("keep/add", to.name) next() })
<template> <router-view v-slot="{ Component }"> <keep-alive :include="includeList"> <component :is="Component" /> </keep-alive> </router-view> </template> <script> export default { computed: { includeList() { return this.$store.getters["keep/include"].join(","); }, }, }; </script>
当然还有页面循环跳转的情况,一般是详情页
A->A->A->A 或A->B->C->A->B->C
这种情况如果不需要保存页面,就用wacth监控$route变化 重新请求接口
如果需要保存页面,就用动态路由addRoute添加新的路由
A1->A2->A3->A4
import time from "../views/time" function copyObj(obj) { if (typeof obj == "object") { if (Array.isArray(obj)) { let arr = []; for (let item of obj) { arr.push(Object.assign(copyObj(item))); } return arr; } else if (obj == null) { return null; } else { let obj1 = {}; for (let index in obj) { obj1[index] = copyObj((obj[index])); } return obj1; } } else if (typeof obj == "function") { return Object.assign(obj); } else if (typeof obj == undefined) { return undefined; } else { return obj; } } window.pushTime = function () { let t = new Date().getTime(); let path = `/time/${t}`; // 深复制component time = copyObj(time) // component name要和route 的name一样 time.name = path this.$router.addRoute({ path, name: path, component: time, }); this.$router.push({ path, }); }
vue2用vue-navigation 非常好用
以上是vue3如何使用keep alive实现前进更新后退销毁的详细内容。更多信息请关注PHP中文网其他相关文章!