首頁 > 軟體

vue3使用keep alive實現前進更新後退銷燬

2022-06-01 18:00:36

keep alive實現前進更新後退銷燬

想要實現前進更新後退銷燬,核心在操作keep-alive的include。
具體做法就是當進入新頁面時將頁面name儲存,再次進入就將它之後的name刪除。

具體實現思路:

正常情況下頁面是線性前進的:

A->B->C->D

include陣列資料[A,B,C,D]

當再次進入C,就認為是D返回C

include陣列資料[A,B,C]

D頁面就被銷燬了,從而實現了後退銷燬

使用vuex儲存include陣列

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>

當然還有頁面迴圈跳轉的情況,一般是詳情頁

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更新銷燬的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com