Vue动态组件以及keep-alive
场景
对动态组件不熟悉的童鞋,提到最常见的tab切换就知道了。一般tab切换实现常用的两种方法:
1 vue-router路由匹配实现
2 动态路由
动态路由:让多个组件使用同一个挂载点,来实现动态切换。
component is
通过 v-bind:is=“组件名” 中的组件名去自动匹配组件,如果匹配不到就不显示。改变挂载的组件,只需要修改is指令的值即可。
<template>
<section class="par-roster menu">
<div>
<div class="test">
<label>分配类型:</label>
<el-radio-group v-model="form.radio" @change="changeRadio($event)" >
<el-radio label="1">定时</el-radio>
<el-radio label="3">实时</el-radio>
<el-radio label="2">临时</el-radio>
</el-radio-group>
</div>
<component :is="form.name" ></component>
</div>
</section>
</template>
<script>
import addAlotList from './addAlotList'
import addrealList from './addrealList'
import addTemList from './addTemList'
export default {
components:{
addAlotList,//定时组件
addrealList,//实时组件
addTemList//临时组件
},
data(){
return{
form:{
name:'addAlotList'
} }
},
methods:{
changeRadio(e){
switch(e){
case '1':
this.form.name='addAlotList'
break
case '2':
this.form.name='addTemList'
break
case '3':
this.form.name='addrealList'
break
}
}
}
}
</script>
改变radio的值,改变is的值从而动态切换组件。
keep-alive缓存
1 基础用法
<keep-alive>
<component :is="form.name" ></component>
</keep-alive>
只需要在外层嵌套标签即可。使用场景:三个定时,临时,实时编辑框可任意切换。那当在定时的页面下添加了一些数据后,又切换到临时页面查看后希望再次回到定时页面时数据仍有保留即缓存不重新渲染。
2 props
include: 字符串或正则表达式,只有名称匹配的组件会被缓存。
exclude: 字符串或正则表达式,任何名称匹配的组件都不会被缓存。
max: 数字,最多可以缓存多少组件实例。
<!-- 逗号分隔字符串 -->
<keep-alive include="addAlotList,addrealList">
<component :is="form.name" ></component>
</keep-alive>
<!-- 正则表达式 -->
<keep-alive :include="/addAlotList|addrealList/">
<component :is="form.name" ></component>
</keep-alive>
<!-- 数组 -->
<keep-alive :exclude="['addAlotList', 'addrealList']">
<component :is="form.name" ></component>
</keep-alive>
<!-- 数组 最大缓存量为10个 -->
<keep-alive :max="10">
<component :is="form.name" ></component>
</keep-alive>