Nuxt3/Vue3动态组件问题:无法为:is属性赋值变量
Vue动态组件
:is属性赋值问题解决 你当前的问题核心在于:Vue3的<script setup>语法中,动态组件的:is属性需要传入组件对象,而非字符串形式的组件名。因为<script setup>里导入的组件不会自动注册到组件的components选项中,用字符串无法匹配到对应的组件。
基础解决方案
直接将导入的组件对象赋值给变量,再传递给:is:
<template> <div class="the-modules"> <component :is="currentComponent" /> </div> </template> <script setup> import ModuleStage from './ModuleStage.vue'; // 直接赋值组件对象,而非字符串 const currentComponent = ModuleStage; </script>
多组件动态切换方案
如果需要切换多个组件,可以用对象映射组件名与组件对象,再根据条件切换:
<template> <div class="the-modules"> <component :is="componentMap[activeComponent]" /> <button @click="activeComponent = 'ModuleStage'">切换到Stage组件</button> <button @click="activeComponent = 'ModuleOther'">切换到Other组件</button> </div> </template> <script setup> import { ref } from 'vue'; import ModuleStage from './ModuleStage.vue'; import ModuleOther from './ModuleOther.vue'; // 用对象建立组件名与组件对象的映射 const componentMap = { ModuleStage, ModuleOther }; // 定义当前激活的组件名 const activeComponent = ref('ModuleStage'); </script>
补充说明:只有在Vue选项式API(非<script setup>)中,且组件已在components选项注册时,才可以用字符串形式的组件名给:is赋值,<script setup>语法下必须使用组件对象。
内容的提问来源于stack exchange,提问作者J. Langer
相关产品推荐
相关产品推荐

