vue3在<script setup>中如何使用动态组件

针对这个问题,其实 vue官方已经给出了说明。
由于组件被引用为变量而不是作为字符串键来注册的,在 <script setup> 中要使用动态组件的时候,就应该使用动态的 :is 来绑定:
// 官方示例
<script setup>
import Foo from './Foo.vue'
import Bar from './Bar.vue'
</script>

<template>
  <component :is="Foo" />
  <component :is="someCondition ? Foo : Bar" />
</template>
什么意思呢?看我的真实示例:
<script setup>
import { reactive } from 'vue'
import Daily from './index/daily.vue'
import Week from './index/week.vue'
import Month from './index/month.vue'

const pageParams = reactive({
	type: 1
})
//注意 这里写的是变量 Daily 而不是字符串 'Daily'
const typeComponentMap = {
	1: Daily,
	2: Week,
	3: Month,
}
</script>

<template>
	<keep-alive>
		<component :is="typeComponentMap[pageParams.type]" />
	</keep-alive>
</template>

官方文档地址https://v3.cn.vuejs.org/api/sfc-script-setup.html#%E4%BD%BF%E7%94%A8%E7%BB%84%E4%BB%B6

Logo

前往低代码交流专区

更多推荐