首頁  >  文章  >  web前端  >  Vue內建元件:keep-alive元件的介紹與使用(附程式碼)

Vue內建元件:keep-alive元件的介紹與使用(附程式碼)

不言
不言原創
2018-08-15 15:26:531749瀏覽

這篇文章帶給大家的內容是關於Vue內建元件:keep-alive元件的介紹與使用(附程式碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所幫助。

keep-alive 簡介

keep-alive是 Vue 內建的元件,可以讓被包含的元件保留狀態,或避免重新渲染。
在vue 2.1.0 版本之後,keep-alive新加入了兩個屬性: include(包含的元件緩存) 與 exclude(排除的元件不緩存,優先權大於include) 。

使用方法

<keep-alive include=&#39;include_components&#39; exclude=&#39;exclude_components&#39;>
  <component>
    <!-- 该组件是否缓存取决于include和exclude属性 -->
  </component>
</keep-alive>

參數解釋
include - 字串或正規表示式,只有名稱匹配的元件會被快取
exclude - 字串或正規表示式,任何名稱匹配的元件都不會被快取
include 和exclude 屬性允許元件有條件地快取。二者都可以用逗號分隔字串、正規表示式或一個陣列來表示。當使用正規或陣列時,一定要使用v-bind !

使用範例

<!-- 逗号分隔字符串,只有组件a与b被缓存。 -->
<keep-alive include="a,b">
  <component></component>
</keep-alive>

<!-- 正则表达式 (需要使用 v-bind,符合匹配规则的都会被缓存) -->
<keep-alive :include="/a|b/">
  <component></component>
</keep-alive>

<!-- Array (需要使用 v-bind,被包含的都会被缓存) -->
<keep-alive :include="[&#39;a&#39;, &#39;b&#39;]">
  <component></component>
</keep-alive>

使用場景

1、儘管可以透過正規則表達式來include和exclude一些元件,但用的更多是透過router.meta屬性明確的指定該元件是否要快取

##router.meta設定

...
    {
        path: 'edit',
        component: () => import('@/views/site/edit'),
        name: 'site.edit',
        meta: {
            title: '网址编辑',
            hidden: true,
            cache: false
        }
    },
    {
        path: 'list',
        component: () => import('@/views/site/list'),
        name: 'site.list',
        meta: {
            title: '网址列表',
            hidden: false,
            cache: true
        }
    },
...
然後透過

v-if標籤來判斷是否需要快取

<!-- 缓存 -->
<keep-alive>
    <router-view v-if="$route.meta.cache"></router-view>
</keep-alive>

<!-- 不缓存 -->
<router-view v-if="!$route.meta.cache"></router-view>
2、不同的頁面切換,刷新規則不同:B->A不刷新, C-A刷新

路由A的設定

{
        path: '/',
        name: 'A',
        component: A,
        meta: {
            cache: true // 需要被缓存
        }
}
元件B配置

export default {
        data() {
            return {};
        },
        methods: {},
        beforeRouteLeave(to, from, next) {
             // 设置下一个路由的 meta
            to.meta.cache = true;  // 让 A 缓存,即不刷新
            next();
        }
};
元件C設定

export default {
        data() {
            return {};
        },
        methods: {},
        beforeRouteLeave(to, from, next) {
            // 设置下一个路由的 meta
            to.meta.cache = false; // 让 A 不缓存,即刷新
            next();
        }
};
注意事項

如果元件被緩存,

created()方法是不會被執行的。而一般我們都會在created方法中去請求數據,加載列表,那麼如果當前頁面緩存了,後台數據有更新,就會造成數據不能及時顯示到前台,這時就需要手動刷新頁面了。 所以元件是否需要快取需要事情而定

export default {
        data() {
            return {};
        },

        created() {
            // do some thing...
        },
        methods: {},
};
相關推薦:

vue 自訂自訂內建元件

vue內建指令使用總結

Vue元件選項props#

以上是Vue內建元件:keep-alive元件的介紹與使用(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn