vue组件keepAlive的使用

需要达到的效果:

列表页------->详情页/修改------>返回列表页(缓存列表页)

其它不缓存

//vuex/index.js

new Vuex.store({
    state: {
        catchPages: []
    },
  mutations: {
        add(state, item) {
            if (state.catchPages.indexOf(item) === -1)
            state.catchPages.push(item);
        },
        remove(state, item) {
            let index = state.catchPages.indexOf(item);
            if(index >0)
            state.catchPages.splice(index, 1)
        }
    },
    actions: {
        add(state, item) {
            state.commit('add', item)
        },
        remove(state, item) {
            state.commit('remove', item)
        },
    },
    getters: {
        catchPages(content){
            return content.catchPages;
        }
    }
})

路由入口的写法:

<!--app.vue-->

<keep-alive :include="$store.getters.catchPages">
        <router-view v-if="$route.meta.keepAlive"></router-view>
</keep-alive>
<router-view v-if="!$route.meta.keepAlive"></router-view>

在路由钩子 beforeRouteLeave 中把需要缓存的组件的name加入 vuex 中的 catchPages 数组中

beforeRouteLeave(to,from,next){
    //do something
  next();
}
原文地址:https://www.cnblogs.com/guojikun/p/9700941.html