vue动态路由*keep-alive

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>
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值