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 {
margin: 20px;
border: 2px solid red;
padding: 20px;
} </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 {
margin: 20px;
border: 2px solid blue;
padding: 20px;
} </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 {
margin: 20px;
border: 2px solid blue;
padding: 20px;
} </style>
测试
访问:http://localhost:8080/
到此,关于“Vue动态组件component标签怎么使用”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
Copyright ©2018 陕西烽火云集信息科技有限公司 版权所有 陕ICP备18009853号-1 增值电信业务经营许可证B1-20180802
烽火云集用户注册协议 法律声明及隐私权政策 致烽火云集用户的一封
法务支持:陕西兰天律师事务所