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

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

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>标签
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44239550/article/details/128652435