Vue动态组件component标签的用法大全

2022-10-14,,

这篇文章主要介绍了Vue动态组件component标签的用法,在Vue中,可以通过component标签的is属性动态指定标签,本文通过示例代码给大家介绍的非常详细,需要的朋友可以参考下

目录
  • 简介
    • 说明
    • 官网网址
  • 示例
    • 路由设置
  • 父组件
    • 子组件

      简介

      说明

      本文介绍Vue的动态组件的用法。

      在Vue中,可以通过component标签的is属性动态指定标签,例如:

      <component :is="componentName"></component>

      此时,componentName的值是什么,就会引入什么组件。

      官网网址

      https://v2.cn.vuejs.org/v2/guide/components.html#动态组件

      示例

      路由设置

      router/index.js

      import Vue from 'vue'
      import VueRouter from 'vue-router'
      import Parent from '../components/Parent'
       
      Vue.use(VueRouter)
       
      const routes = [
        {
          path: '/',
          name: 'Parent',
          component: Parent
        }
      ]
       
      const router = new VueRouter({
        routes
      })
       
      export default router

      父组件

      components/Parent.vue

      <template>
        <div class="outer">
          <h2>这是父组件</h2>
          <component :is="componentName" :propA="propAValue"></component>
        </div>
      </template>
       
      <script>
      import ChildA from './ChildA'
      import ChildB from './ChildB'
       
      export default {
        name: 'Parent',
        components: { ChildA, ChildB },
        data () {
          return {
            componentName: 'ChildB',
            propAValue: 'aaa'
          }
        }
      }
      </script>
       
      <style scoped>
      .outer {
        margin: 20px;
        border: 2px solid red;
        padding: 20px;
      }
      </style>

      子组件

      components/ChildA.vue

      <template>
        <div class="outer">
          <h3>这是ChildA</h3>
          <div>传入进来的propA值为:{{propA}}</div>
        </div>
      </template>
       
      <script>
      export default {
        name: 'ChildA',
        props: ['propA']
      }
      </script>
       
      <style scoped>
      .outer {
        margin: 20px;
        border: 2px solid blue;
        padding: 20px;
      }
      </style>

      components/ChildA.vue

      <template>
        <div class="outer">
          <h3>这是ChildB</h3>
          <div>传入进来的propA值为:{{propA}}</div>
        </div>
      </template>
       
      <script>
      export default {
        name: 'ChildB',
        props: ['propA']
      }
      </script>
       
      <style scoped>
      .outer {
        margin: 20px;
        border: 2px solid blue;
        padding: 20px;
      }
      </style>

      测试

      访问:http://localhost:8080/

      到此这篇关于Vue动态组件component标签的用法大全的文章就介绍到这了,更多相关Vue--动态组件component标签内容请搜索北冥有鱼以前的文章或继续浏览下面的相关文章希望大家以后多多支持北冥有鱼!

      您可能感兴趣的文章:

      • vue中动态组件使用及传值方式
      • Vue动态组件与内置组件浅析讲解
      • vue中使用keep-alive动态删除已缓存组件方式
      • vue中缓存组件keep alive的介绍及使用方法
      • Vue组件开发之异步组件详解
      • Vue动态组件和异步组件原理详解
      • Vue异步组件使用详解
      • Vue浅析讲解动态组件与缓存组件及异步组件的使用

      《Vue动态组件component标签的用法大全.doc》

      下载本文的Word格式文档,以方便收藏与打印。