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

      简介

      说明

      本文介绍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标签的用法大全

      声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。