0
点赞
收藏
分享

微信扫一扫

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

书坊尚 2022-04-08 阅读 58

课程回顾

课程主要内容

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>

效果:

 


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

举报

相关推荐

0 条评论