vue学习笔记之内置组件篇(component&keep-alive)

165 阅读1分钟

1. component

<component></component>内置组件一般和is绑定属性结合使用,产生动态组件的效果

<body>
    <div id='app'>
        <div>
            <!-- 注意 currentTab = tab是内联js语句,执行后currentTab发生变化触发currentTabComponent -->
            <button v-for="tab in tabs" @click="currentTab = tab">
                {{ tab }}
            </button>
            <!-- component为vue的内置组件和特殊属性is搭配起来表示
                根据currentTabComponent的变化进而渲染成不同的组件,完全替换掉内置的component组件
            -->
            <component :is="currentTabComponent"></component>
        </div>
    </div>

    <script>
        Vue.component("home", {
            template: "<div>Home component</div>"
        });
        Vue.component("posts", {
            template: "<div>Posts component</div>"
        });
        new Vue({
            el: "#app",
            data: {
                currentTab: "Home",
                tabs: ["Home", "Posts"]
            },
            computed: {
                currentTabComponent: function () {
                    return this.currentTab.toLowerCase();
                }
            }
        });
    </script>
</body>

2. keep-alive

在 2.2.0 及其更高版本中,activateddeactivated 将会在 <keep-alive> 树内的所有嵌套组件中触发

注意<keep-alive> 不会在函数式组件中正常工作,因为它们没有缓存实例。

属性

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

用法<keep-alive> 包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。主要用于保留组件状态或避免重新渲染。

<keep-alive> 是一个抽象组件,它自身不会渲染一个 DOM 元素,也不会出现在组件的父组件链中。

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

匹配首先检查组件自身的 name 选项,如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)。匿名组件不能被匹配。

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