vue 动态组件

  • 动态组件就是几个组件放在一个挂载点下,然后根据父组件的某个变量来决定显示哪个,或者都不显示。
  • 在挂载点使用 component 标签,然后使用 is =“组件名”,它会自动去找匹配的组件名,如果有,则显示;

看例子:

<!-- html部分 -->

<div id="app">
    <component is="one"></component>
</div>
// js 部分

new Vue({
    el: '#app',
    components: {
        one: {template: '<div>我是线路一</div>'},
        two: {template: '<div>我是线路二</div>'},
        thr: {template: '<div>我是线路三</div>'}
    }
})

上面代码注册了三个组件,在 component 标签里有个属性 is,is=one,所以页面会渲染名字叫 one 的组件,显示结果如下:

我是线路一

如果给 is 属性绑定动态值,那么就可以实现组件的动态切换,例子如下:

<!-- html 部分 -->

<div id="app">
    <button v-for="item in tabs" @click="change = item.id">
    	{{ item.text }}
    </button>
    <component :is="change"></component>
</div>
// js 部分

new Vue({
  el: '#app',
  data: {
  	change: 'one' // 默认显示组件 one
    tabs: [
    	{id: 'one', text: '线路一'},
        {id: 'two', text: '线路二'},
        {id: 'thr', text: '线路三'}
    ]
  },
  components: {
  	one: {template: '<div>我是线路一</div>'},
    two: {template: '<div>我是线路二</div>'},
    thr: {template: '<div>我是线路三</div>'}
  }
})

上面代码用 v-bind 给属性 is 动态传递了值,实现了组件的动态切换,效果如下:

在这里插入图片描述

  • 13
    点赞
  • 38
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值