Home >Web Front-end >Vue.js >How vue3 uses keep alive to achieve forward update and backward destruction
If you want to realize forward update and backward destruction, the core is to operate the include of keep-alive.
The specific method is to save the page name when entering a new page, and delete the name after it when entering again.
Under normal circumstances, the page advances linearly:
A->B->C->D
include Array data [A,B,C,D]
When entering C again, it is considered that D returns to C
include array data[A,B,C]
D The page is destroyed, thus achieving backward destruction
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>
Of course, there are also cases where the page jumps in a loop, usually the details page
A->A->A->A or A->B->C->A-> B->C
In this case, if you don’t need to save the page, use wacth to monitor $route changes and re-request the interface
If you need to save the page, use dynamic routing addRoute to add a new route
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 is very easy to use with vue-navigation
The above is the detailed content of How vue3 uses keep alive to achieve forward update and backward destruction. For more information, please follow other related articles on the PHP Chinese website!