白城市住房建设局网站广州seo成功案例
嘿,happy
文章目录
- 一、动态组件
- 二、keep-alive
一、动态组件
动态组件是使用
component
组件,通过一个特殊的属性is
来实现
- 一定是注册好的组件
- 我们需要将属性和监听事件放到
component
上来使用
<template><div><button v-for="tab in tabs" :key="tab":class="{active: currentTab === tab}"@click="tabClick(tab)">{{tab}}</button><component :is="currentTab"/></div>
</template><script>import Home from "./pages/Home.vue";import About from "./pages/About.vue";import Category from "./pages/Category.vue";export default {components: {Home, About, Category},data() {return {tabs: ["home", "about", "category"],currentTab: "home"}},methods: {tabClick(tab) {this.currentTab = tab;},}}
</script><style scoped>.active {color: red;}
</style>
二、keep-alive
- keep-alive 是 Vue 的内置组件,当它包裹动态组件时,会缓存不活动的组件实例,而不是销毁它们。
- 和 transition 相似,keep-alive 是一个抽象组件:它自身不会渲染成一个 DOM 元素,也不会出现在父组件链中。
作用: 在组件切换过程中将状态保留在内存中,防止重复渲染DOM,减少加载时间及性能消耗,提高用户体验性。
原理:
在 created 函数调用时将需要缓存的 VNode 节点保存在 this.cache 中/在 render(页面渲染) 时,如果 VNode 的 name
符合缓存条件(可以用 include 以及 exclude 控制),则会从 this.cache 中取出之前缓存的 VNode 实例进行渲染。
keep-alive有一些属性 :
- include 只有 名称匹配的组件会被缓存;
- exclude 任何名称匹配的组件都不会被缓存;
- max 最多可以缓存多少组件实例,一旦达到这个数字,那么缓存组件中最近没有被访问的实例会被销毁;
- include 和 exclude prop 允许组件有条件地缓存:
二者都可以用逗号分隔字符串、正则表达式或一个数组来表示
- 匹配首先检查组件自身的 name 选项;
- 如果 name 选项不可用,则匹配它的局部注册名称 (父组件 components 选项的键值)
// 逗号分隔字符串
<keep-alive include="a,b"><component :is="view"></component>
</keep-alive>// regex (使用 `v-bind`) -->
<keep-alive :include="/a|b/"><component :is="view"></component>
</keep-alive>// Array (使用 `v-bind`)
<keep-alive :include="['a', 'b']"><component :is="view"></component>
</keep-alive>