keep-alive 和 动态组件

233 阅读1分钟

keep-alive

<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。和 <transition> 相似,<keep-alive> 是一个抽象组件:它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中。

当组件在 <keep-alive> 内被切换,它的 activated 和 deactivated 这两个生命周期钩子函数将会被对应执行。

<keep-alive> 要求同时只有一个子元素被渲染。

  • include - 字符串或正则表达式。只有名称匹配的组件会被缓存。
  • exclude - 字符串或正则表达式。任何名称匹配的组件都不会被缓存。
  • max - 数字。最多可以缓存多少组件实例。

include和exclude传值注意

<!-- 逗号分隔字符串 --> 
<keep-alive include="a,b"> 
    <component :is="view"></component> 
</keep-alive> 
<!-- 正则表达式 (使用 `v-bind`) --> 
<keep-alive :include="/a|b/"> 
    <component :is="view"></component> 
</keep-alive> 
<!-- 数组 (使用 `v-bind`) --> 
<keep-alive :include="['a', 'b']"> 
    <component :is="view"></component> 
</keep-alive>

max属性

最多可以缓存多少组件实例。一旦这个数字达到了,在新实例被创建之前,已缓存组件中最久没有被访问的实例会被销毁掉。

<keep-alive :max="10">
  <component :is="view"></component>
</keep-alive>

动态组件

<!DOCTYPE html>

<html>

<head>

<title>Dynamic Components Example</title>

<script src="https://unpkg.com/vue@2"></script>

<style>

.tab-button {

    padding: 6px 10px;

    border-top-left-radius: 3px;

    border-top-right-radius: 3px;

    border: 1px solid #ccc;

    cursor: pointer;

    background: #f0f0f0;

    margin-bottom: -1px;

    margin-right: -1px;

}

.tab-button:hover {

    background: #e0e0e0;

}

.tab-button.active {

    background: #e0e0e0;

}

.tab {

    border: 1px solid #ccc;

    padding: 10px;

}

</style>

</head>

<body>

    <div id="dynamic-component-demo" class="demo">

        <button

        v-for="tab in tabs"

        v-bind:key="tab"

        v-bind:class="['tab-button', { active: currentTab === tab }]"

        v-on:click="currentTab = tab"

        >

        {{ tab }}

        </button>
        <component v-bind:is="currentTabComponent" class="tab"></component>

    </div>
<script>

    Vue.component("tab-home", {

    template: "<div>Home component</div>"

    });

    Vue.component("tab-posts", {

    template: "<div>Posts component</div>"

    });

    Vue.component("tab-archive", {

    template: "<div>Archive component</div>"

    });
    
    new Vue({

        el: "#dynamic-component-demo",

        data: {

        currentTab: "Home",

        tabs: ["Home", "Posts", "Archive"]

        },

        computed: {

        currentTabComponent: function() {

        return "tab-" + this.currentTab.toLowerCase();

        }

    }

});

</script>

</body>

</html>