vue中的动态组件

1. 动态组件是由vue内置标签component上的is属性确定的,is属性的值,就是组件的名字

第二种方法,用v-for,需要注意的是,type的值只是用来做标识的

    <div id="app">
        <component :is="type"></component>
       <!-- <child-one v-if="type === 'child-one'"></child-one>
       <child-two v-if="type === 'child-two'"></child-two> -->
       <button @click="toggle">click me</button>
    </div>
    <script>    
        Vue.component( 'child-one', {
            template: `<div>child-one</div>`,
        })
        Vue.component('child-two', {
            template: `<div>child-two</div>`
        })
        var vm = new Vue({
            el: '#app',
            data: {
                type: 'child-one'
            },
            methods: {
                toggle(){
                    this.type = (this.type === 'child-one' ? this.type = 'child-two' : this.type = 'child-one')
                }
            }
        })
    </script>

同时要注意:局域组件好像不可以实现动态组件,刚用局域组件写的时候,总是报错

上述的切换存在一定的问题:组件一和组件二来回切换的过程,底层原理是:销毁一个创建一个,然后点击切换的过程中其实就是销毁和创建的切换,这样非常浪费性能

(1)知识点:v-once,作用:带有v-once指令的标签,会缓存,这样下次调用该标签的时候,直接去缓存中取

    <div id="app">
        <!-- <component :is="type"></component> -->
       <child-one v-if="type === 'child-one'"></child-one>
       <child-two v-if="type === 'child-two'"></child-two>
       <button @click="toggle">click me</button>
    </div>
    <script>    
        Vue.component( 'child-one', {
            template: `<div v-once>child-one</div>`,
        })
        Vue.component('child-two', {
            template: `<div v-once>child-two</div>`
        })
        var vm = new Vue({
            el: '#app',
            data: {
                type: 'child-one'
            },
            methods: {
                toggle(){
                    this.type = (this.type === 'child-one' ? this.type = 'child-two' : this.type = 'child-one')
                }
            }
        })
    </script>

(2)可以通过<keep-alive>标签来缓存动态组件

<keep-alive>
    <component :is="type"></component>
</keep-alive>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值