跟着技术胖学Vue2.0—第二季第九课:Component标签

课程回顾

课程主要内容

1、使用component标签变换组件。

2、使用按钮动态变换组件。

课程展开

1、使用component标签变换组件

当我们声明了多个组件的时候,可以直接使用component标签来选择要用到的组件,而不用使用特定的组件名。

首先,我们先在外部定义三个组件,然后在Vue构造器中声明一下。

        var componentA = {
            template:`<div style='color:red'>This is componentA.</div>`
        }
        var componentB = {
            template:`<div style='color:green'>This is componentB.</div>`
        }
        var componentC = {
            template:`<div style='color:orange'>This is componentC.</div>`
        }
        var app = new Vue({
            el:'#app',
            components:{
                'componentA':componentA,
                'componentB':componentB,
                'componentC':componentC
            }
        })

这时要使用component标签选择对应的组件就需要使用v-bind绑定到is属性上,这个属性用于绑定特定组件名。如下:

html:

<div id="app">
     <component :is="who"></component>
</div>

script:

var app = new Vue({
            el:'#app',
            data:{
                who:'componentC'
            }
})

效果:

 2、使用按钮动态变换组件

对上面的例子扩展一下,我们在html中添加一个按钮,当点击按钮的时候,就变换一下组件。这个功能需要在button的click事件中通过判断来实现,如下:

script:

methods:{
                changeComponent:function(){
                    if(this.who=='componentA'){
                        this.who='componentB'
                    }else if(this.who=='componentB'){
                        this.who='componentC'
                    }else{
                        this.who='componentA'
                    }
                }
}

html:

<div id="app">
        <component :is="who"></component>
        <p><button @click="changeComponent">changeComponent</button></p>
</div>

效果:

 


以上就是第九课的内容,也是第二季的最后一节课,下次就将进入到第二季的复习啦! 趁着时间充足抓紧时间写代码哈哈哈哈~

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值