温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

vue如何使用keep-alive后清除缓存

发布时间:2021-08-10 09:07:08 来源:亿速云 阅读:1561 作者:小新 栏目:开发技术

小编给大家分享一下vue如何使用keep-alive后清除缓存,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

什么是keepalive?

在平常开发中,有部分组件没有必要多次初始化,这时,我们需要将组件进行持久化,使组件的状态维持不变,在下一次展示时,也不会进行重新初始化组件。

也就是说,keepalive 是 Vue 内置的一个组件,可以使被包含的组件保留状态,或避免重新渲染 。也就是所谓的组件缓存

基本用法

<keep-alive>
    <component />  //你的组件
</keep-alive>

需求:从列表页进入详情页,再返回列表页时保留查询条件,但在切换其他tab时,清空查询条件。

解决:保留查询条件很简单,直接引入keep-alive,但是清除的话,vue本身没有api直接清除,所以要单独处理。

参考文章:http://aspedrom.com/5HD5

router/index,拦截路由并做处理:

beforeRouteLeave:function(to, from, next){
    // 增加离开路由时清除keep-alive
    if (from && from.meta.rank && to.meta.rank && from.meta.rank == to.meta.rank)
    {//此处判断是如果返回上一层,你可以根据自己的业务更改此处的判断逻辑,酌情决定是否摧毁本层缓存。
        if (this.$vnode && this.$vnode.data.keepAlive)
        {
            if (this.$vnode.parent && this.$vnode.parent.componentInstance && this.$vnode.parent.componentInstance.cache)
            {
                if (this.$vnode.componentOptions)
                {
                    var key = this.$vnode.key == null
                                ? this.$vnode.componentOptions.Ctor.cid + (this.$vnode.componentOptions.tag ? `::${this.$vnode.componentOptions.tag}` : '')
                                : this.$vnode.key;
                    var cache = this.$vnode.parent.componentInstance.cache;
                    var keys  = this.$vnode.parent.componentInstance.keys;
                    if (cache[key])
                    {
                        if (keys.length) {
                            var index = keys.indexOf(key);
                            if (index > -1) {
                                keys.splice(index, 1);
                            }
                        }
                        delete cache[key];
                    }
                }
            }
        }
        this.$destroy();
    }
    next();
},

同时在路由中添加meta:

{
    // 账号列表
    path: '/account',
    name: 'account',
    component: () => import('../views/account/index.vue'),
    meta: { title: '账号列表' ,rank:1.5}
  },
  {
    // 添加账号
    path: '/accountadd',
    name: 'accountadd',
    component: () => import('../views/account/add.vue'),
    meta: { title: '添加账号' ,rank:2.5}
  },
  {
    // 编辑账号
    path: '/accountedit/:id',
    name: 'accountedit',
    component: () => import('../views/account/add.vue'),
    meta: { title: '编辑账号' ,rank:2.5}
  },
  {
    // 角色列表
    path: '/role',
    name: 'role',
    component: () => import('../views/role/index.vue'),
    meta: { title: '角色列表' ,rank:1.5}
  },

以上是“vue如何使用keep-alive后清除缓存”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI