美文网首页VUE
Vue动态组件

Vue动态组件

作者: cain07 | 来源:发表于2021-07-18 22:02 被阅读0次

    Vue中提供了<component>来挂载不同组件,使用 is 选择要展示的组件

    效果

    image

    案例

    index.vue

    <template>
      <div>
          <component :is="cmpName"></component> <br/>
          <button @click="changeCmp('cmpone')">第一个组件</button>
          <button @click="changeCmp('cmptwo')">第二个组件</button>
          <button @click="changeCmp('cmpthree')">第三个组件</button>
      </div>
    </template>
    <script>
    // 导入子组件
    import cmpone from './cmpone'
    import cmptwo from './cmptwo '
    import cmpthree from './cmpthree '
    export default {
      // 注册组件
      components: {
        cmpone,
        cmptwo,
        cmpthree 
      },
      methods: {
        changeCmp(cmpName) {
          this.cmpName = cmpName
        }
      },
      data(){
        return {
          cmpName: 'cmpone' //默认显示第一个组件
        }
      }
    }
    </script>
    
    

    cmpone.vue

    <template>
      <div>这是子组件1</div>
    </template>
    
    

    cmptow.vue

    <template>
      <div>这是子组件2</div>
    </template>
    
    

    cmpthree.vue

    <template>
      <div>这是子组件3</div>
    </template>
    

    作者:圆梦人生
    链接:https://www.jianshu.com/p/28ee8444d957
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    相关文章

      网友评论

        本文标题:Vue动态组件

        本文链接:https://www.haomeiwen.com/subject/klyzpltx.html