动态加载组件以及是否将变化进行缓存

动态组件加载有点像操作元素一样,没什么特别的

CompParent.vue代码:

<template>
    <div>
        <h3>动态组件加载component</h3>
        <!-- <CompA></CompA>
        <hr>
        <CompB></CompB> -->
        <button @click="change()">切换</button>
        <hr>
        <keep-alive>
            <component :is="showComp"></component> 
        </keep-alive>
    </div>
</template>

<script>
import CompA from './CompA.vue';
import CompB from './CompB.vue';
export default {
    components: { 
        CompA,
        CompB
    },
    data(){
        return{
            showComp:"CompA"
        }
    },
    methods:{
        
        change(){
            // if(this.showComp == "CompA"){
            //     this.showComp = "CompB"
            // }else{
            //     this.showComp = "CompA"
            // }
            this.showComp = this.showComp == "CompA" ? "CompB" : "CompA"
        }
    }
   
}
</script>

<style>

</style>

CompA.vue代码:

<template>
    <div>
        <h5>组件A</h5> 
        <button @click="num = num -5">减少5个</button>
        <h5>{{ num }}</h5>
    </div>
</template>

<script>
export default {
    data(){
        return{
            num:100
        }
    }
}
</script>

<style>

</style>

CompB.vue代码:

<template>
    <div>
        <h5>组件B</h5>
        <button @click="num = num + 7">增加7个</button>
        <h5>{{ num }}</h5>
    </div>
</template>

<script>
export default {
    data() {
        return {
            num: 100
        }
    }
}
</script>

<style>

</style>

效果:


这是组件A, 减少到了70
在这里插入图片描述


这是组件B 增加到了121
在这里插入图片描述
再次切换回A,内容进行了缓存,因为使用了<keep-alive>标签
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值