Vue动态组件coomponent标签怎么使用

2022-08-25 09:15:04

说明

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

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

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

示例

路由设置

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">     <h3>这是父组件</h3>     <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 {
  margin20px;
  border2px solid red;
  padding20px;
} </style>

子组件

components/ChildA.vue

<template>   <div class="outer">     <h4>这是ChildA</h4>     <div>传入进来的propA值为:{{propA}}</div>   </div> </template>   <script> export default {
  name'ChildA',
  props: ['propA']
} </script>   <style scoped> .outer {
  margin20px;
  border2px solid blue;
  padding20px;
} </style>

components/ChildA.vue

<template>   <div class="outer">     <h4>这是ChildB</h4>     <div>传入进来的propA值为:{{propA}}</div>   </div> </template>   <script> export default {
  name'ChildB',
  props: ['propA']
} </script>   <style scoped> .outer {
  margin20px;
  border2px solid blue;
  padding20px;
} </style>

测试

访问:http://localhost:8080/

到此,关于“Vue动态组件component标签怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!