vue3使用keep?alive實現(xiàn)前進(jìn)更新后退銷毀
keep alive實現(xiàn)前進(jìn)更新后退銷毀
想要實現(xiàn)前進(jìn)更新后退銷毀,核心在操作keep-alive的include。
具體做法就是當(dāng)進(jìn)入新頁面時將頁面name保存,再次進(jìn)入就將它之后的name刪除。
具體實現(xiàn)思路:
正常情況下頁面是線性前進(jìn)的:
A->B->C->D
include數(shù)組數(shù)據(jù)[A,B,C,D]
當(dāng)再次進(jìn)入C,就認(rèn)為是D返回C
include數(shù)組數(shù)據(jù)[A,B,C]
D頁面就被銷毀了,從而實現(xiàn)了后退銷毀
使用vuex保存include數(shù)組
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
在beforeEach中添加name
import store from "../store" router.beforeEach((to, from,next) => { // 頁面name要和route 的name一樣 store.commit("keep/add", to.name) next() })
include使用
<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>
當(dāng)然還有頁面循環(huán)跳轉(zhuǎn)的情況,一般是詳情頁
A->A->A->A 或A->B->C->A->B->C
這種情況如果不需要保存頁面,就用wacth監(jiān)控$route變化 重新請求接口
如果需要保存頁面,就用動態(tài)路由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}`; // 深復(fù)制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實現(xiàn)前進(jìn)更新后退銷毀的詳細(xì)內(nèi)容,更多關(guān)于vue3 keep alive更新銷毀的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vue中關(guān)于router.beforeEach()的用法
這篇文章主要介紹了vue中關(guān)于router.beforeEach()的用法,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11Vue實現(xiàn)監(jiān)聽dom節(jié)點寬高變化方式
這篇文章主要介紹了Vue實現(xiàn)監(jiān)聽dom節(jié)點寬高變化方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10