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
}

 

转载于:https://www.cnblogs.com/lw5116/p/11592918.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值