您好,登錄后才能下訂單哦!
這篇文章主要講解了“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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。