1. 程式人生 > 程式設計 >vue使用keep-alive後清除快取的方法

vue使用keep-alive後清除快取的方法

什麼是keepalive?

在平常開發中,有部分元件沒有必要多次初始化,這時,我們需要將元件進行持久化,使元件的狀態維持不變,在下一次展示時,也不會進行重新初始化元件。

也就是說,keepalive 是 內建的一個元件,可以使被包含的元件保留狀態,或避免重新渲染 。也就是所謂的元件快取

基本用法

<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}` : '')
                                : thishttp://www.cppcns.com
.$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',meta: { title: '編輯賬號',{
    // 角色列表
    path: '/role',name: 'role',component: () => import('../views/role/index.vue'),meta: {http://www.cppcns.com title: '角色列表',

總結

到此這篇關於vue使用keep-alive後清除快取的文章就介紹到這了,更多相關keep-alive清除快取內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!