您好,登录后才能下订单哦!
这篇文章主要讲解了“vue3如何使用keep alive实现前进更新后退销毁”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“vue3如何使用keep alive实现前进更新后退销毁”吧!
想要实现前进更新后退销毁,核心在操作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实现前进更新后退销毁”的内容了,经过本文的学习后,相信大家对vue3如何使用keep alive实现前进更新后退销毁这一问题有了更深刻的体会,具体使用情况还需要大家实践验证。这里是亿速云,小编将为大家推送更多相关知识点的文章,欢迎关注!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。