这篇文章主要介绍了 vue 动态组件component ,vue提供了一个内置的<component>,专门用来实现动态组件的渲染,这个标签就相当于一个占位符,需要使用is属性指定绑定的组件,想了解更多详细内容的小伙伴请参考下面文章的具体内容
- component
 
如何实现动态组件渲染
vue提供了一个内置的<component> ,专门用来实现动态组件的渲染。
这个标签就相当于一个占位符,需要使用is属性指定绑定的组件
<button @click="comName = 'Left'">展示Left</button>
<button @click="comName = 'Right'">展示Right</button>
<div class="box">
    <!-- 渲染Left组件和Right组件 -->
    <!-- component组件是Vue内置的 -->
    <!-- is表示要渲染的组件的名字 -->
    <component :is="comName"></component>
</div>
<script>
    import Left from '@/compeonents/Left.vue'
    import Right from '@/components/Right.vue'
    export default {
        components: {
            Left,
            Right
        },
        data() {
            return {
                //comName 表示要展示的组件的名字
                comName: Left,
            }
        }
    }
</script>
 
   - keep-alive
 
- 存在的问题
 
当在Left组件中实现一个按钮加一的功能,加一操作后切换组件,再切回来
如下是Left中加一功能
<div class="left-container">
    <h3>Left 组件 ---- {{ count }}</h3>
    <button @click="count += 1">+1</button>
</div>
<script>
    export default {
        data(){
            return {
                count: 0
            }
        }
    }
</script>
 操作,进行加一操作后切换到right组件,再切换回来,发现组件中的数据被重写初始化了
使用Vue的生命周期查看Left组件
如下是Left中添加生命周期函数
export default {
    created() {
        console.log('Left 组件被创建了!')
    },
    destoryed(){
        console.log('Left 组件被销毁了~')
    }
}
 
   
   存在的问题: 在切换组件的同时会销毁和创建组件,这样每次切换到同一组件时得到的组件对象就不是同一个了,会重写初始化数据
- 使用keep-alive解决
 
keep-alive 组件也是Vue内置的组件,可以直接使用
在App根组件中如下修改:
<keep-alive>
    <!-- keep-alive 可以把内部的组件进行缓存,而不是销毁组件 -->
    <component :is="comName"></component>
</keep-alive>
 
   - keep-alive的生命周期
 
该生命周期,只有在组件使用了keep-alive时才能使用
deactivated当组件被缓存时,自动触发
actived当组件被激活时,自动触发
在Left组件中添加如下修改
//当组件第一次被创建时,会先触发created,后触发activated
//当组件被激活时,只会触发activated,不触发created
activated() {
    console.log('组件被激活了,activated')
},
deactivated(){
    console.log('组件被缓存了,deactivated')
}
 
   - keep-alive 的 include, exclude属性
 
keep-alive默认会缓存所有被keep-alive包裹的component里的组件
如何指定需要缓存的组件呢:
使用include / exclude 属性,不能同时使用
<keep-alive include="Left,MyRight">
    <component :is="comName"></component>
</keep-alive>
 以上指定了需要缓存的组件名称: 注意这里的组件的名称
Left组件中:
export default{}
 Right组件中:
export default{
    //当提供了name属性后,组件的名称就是name属性的值
    name: 'MyRight'
}
 区分: 组件内name属性,和组件外注册名 的关系
组件外:
import Left '@/components/Left.vue'
components: {
    Left,
}
 这里的注册名只用于组件的引用,如果组件内没有name属性那么name默认就是注册名
export default{
    //当提供了name属性后,组件的名称就是name属性的值
    name: 'MyRight'
}



















