说明

  • component为vue内置特殊元素,一个用于渲染动态组件或元素的’元组件’
  • 具体可以看@官网

使用

  • 大概使用就是使用component当中的属性is,这个is可以传入字符串,也可以传入组件

    • <component :is="showChildA"/>其中 showChildA为一个组件
  • 示例

    • 根据不同的参数来决定渲染哪一个组件

App.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div>
我是主页
<component :is="showComponent"></component>
</div>
</template>

<script setup>
import {ref,computed} from "vue";
import ChildA from "./pages/ChildA.vue"
import ChildB from "./pages/ChildB.vue"
const componentAll = {
son1:ChildA,
son2:ChildB,
}

const receiveTitle = ref('son1');//假设从别的地方接收到一个属性

const showComponent = computed(()=>{
return componentAll[receiveTitle.value]
})
console.log(showComponent);
</script>

<style scoped>
</style>

ChildA.vue

1
2
3
4
5
6
7
8
<template>
<div>
<h1>我是ChildA</h1>
</div>
</template>

<script setup>
</script>

ChildB.vue

1
2
3
4
5
6
7
8
<template>
<div>
<h1>我是ChildB</h1>
</div>
</template>

<script setup>
</script>