网络编程
位置:首页>> 网络编程>> JavaScript>> Vue动态组件component标签的用法大全

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

作者:IT利刃出鞘  发布时间:2024-05-29 22:28:33 

标签:Vue,动态组件,component

简介

说明

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

来源:https://blog.csdn.net/feiying0canglang/article/details/126255761

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com