Vue动态组件component标签

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Vue动态组件component标签

IT利刃出鞘   2022-09-29 我要评论

简介

说明

本文介绍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/

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们