1、动态渲染组件
<component :is=""></component>
通过isShow来切换显示A、B组件
首先创建父组件.vue文件和两个子组件A、B文件,并引入。
template:
<div>
<h3>我是父组件dynamicComp.vue</h3>
<button @click="isShow = !isShow">切换组件</button>
<!-- isShow为true时显示childA组件,否则显示childB组件 -->
<component :is="isShow ? childA : childB"></component>
</div>
js:
import { ref, reactive, shallowRef } from 'vue'
import childA from './component/childA.vue'
import childB from './component/childB.vue'
const isShow = ref(true)
效果:
点击切换按钮,就会切换显示A、B组件。
2、整理要渲染的组件 --案例
通过整理组件名到一个变量,再用:is渲染
不引入shallowRef跳过proxy代理的话会报警告
2.1 新建C、D、E子组件:
~childC:
<template>
<div>
<h3>我是组件childC</h3>
<img src="@/assets/images/pig.jpg" alt="">
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
</script>
<style scoped>
img {
width: 50px;
height: 50px;
}
</style>
~childD:
<template>
<div>
<h3>我是组件childD</h3>
<ul>
<li>电影</li>
<li>体育</li>
<li>图书</li>
<li>电竞</li>
<li>编程</li>
</ul>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
</script>
<style scoped>
</style>
~childE:
<template>
<div>
<h3>我是组件childE</h3>
<input type="text" placeholder="请输入...">
</div>
</template>
<script setup>
import { ref, reactive } from 'vue'
</script>
<style scoped>
</style>
父组件:
html:
<div>######################整理要渲染的组件 --案例 start ################</div>
<div>
<button @click="handleChangeTag('C')">组件C</button>
<button @click="handleChangeTag('D')">组件D</button>
<button @click="handleChangeTag('E')">组件E</button>
<component :is="componentTag"></component>
</div>
<div>######################整理要渲染的组件 --案例 end ################</div>
js:
import { ref, reactive, shallowRef } from 'vue'
import childA from './component/childA.vue'
import childB from './component/childB.vue'
import childC from './component/childC.vue'
import childD from './component/childD.vue'
import childE from './component/childE.vue'
/**
* 2、整理要渲染的组件 --案例
* 通过整理组件名到一个变量,再用:is渲染
* 不引入shallowRef跳过proxy代理的话会报警告
*/
const componentTag = shallowRef(childC)
// const componentTag = ref(childC) //如果用ref,此处被警告节省性能开销
const handleChangeTag = (idx) => {
componentTag.value = (idx === 'C') ? childC : (idx === 'D' ? childD : childE)
}
效果:
默认显示childC组件,点击切换就显示对应组件。