• vue的keep-alive实现框架页签功能


    在web页面实现类似于浏览器的页签功能,使用vue的keep-alive组件做缓存

    基本实现如下:

    1.将需要做缓存的视图用keep-alive包裹

    <keep-alive :include="keepAliveComponents">
                  <router-view></router-view>
              </keep-alive>

    2.视图通过路由配置。需要缓存的组件在meta的keepAlive设为true,注意需要设置name

    const routes = [
        {
            path: "/talentPool",
            component: TalentPool,
            name: 'TalentPool',
            meta: {
                keepAlive: true,
                title: "人才池",
                pageCode: "TalentPool"
            }
        }
    ];

    3.如果需要动态更改缓存组件的,即有的情景下需要缓存,有的情景下不需要缓存,则需要做一个动态数组去控制

    分别在路由跳转前和跳转后做处理,这里使用了vuex,需要缓存的组件名数组存在store里(注意是存的是组件名,keep-alive的include方式识别的是组件名)

    router.beforeEach((to, from, next) => {
        /* 路由发生变化修改页面title */
        if (to.meta.title) {
            document.title = to.meta.title;
        }
        if(from.path == '/'){
            to.name && store.commit('keepAlive/noKeepAlive', to.name);
            if(to.name == 'FloatingListMyRecommend'){
                store.commit('keepAlive/noKeepAlive', 'FloatingListRecommendToMe');
            }
        }
        next();
    });
    router.afterEach((to, from) => {
        setTimeout(() => {
            if(to.name !== 'WorkTableHome'){
                to.name && store.commit('keepAlive/keepAlive', to.name);
            }
    
        }, 1000);
    });

    这里使用了延时器是由于不做延时就无法生效。

    vuex的相关设置

    const state = {
        keepAliveComponents: []//需要缓存的数组
    }
    
    const getters = {
        keepAliveComponents(state){
            return state.keepAliveComponents;
        }
    }
    
    const actions = {
        invokeKeepAlive({ commit, state }, component) {
            commit('keepAlive', component);
        },
        invokeNoKeepAlive({ commit, state }, component) {
            commit('noKeepAlive', component);
        },
    }
    
    const mutations = {
        keepAlive (state, component) {
            !state.keepAliveComponents.includes(component) &&
                state.keepAliveComponents.push(component)
        },
        noKeepAlive (state, component) {
            const index = state.keepAliveComponents.indexOf(component)
            index !== -1 &&
                state.keepAliveComponents.splice(index, 1)
        }
    
    }
    
    export default {
        namespaced:true,
        state,
        getters,
        actions,
        mutations
    }
  • 相关阅读:
    第四周助教小结
    java课程总结
    第十四周总结
    第十三周实验报告
    第十二周课程报告
    第十一周课程总结
    第十周课程总结
    第九周课程总结&实验报告(七)
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
  • 原文地址:https://www.cnblogs.com/lw5116/p/11592918.html
Copyright © 2020-2023  润新知