vue3 js 组件:组件未更新
P粉779565855
P粉779565855 2024-02-25 14:50:02
0
2
398

我有一个从 API 收集数据的组件。从 API 返回的数据是一个包含详细信息的数组。数组中的值之一是应呈现的组件的类型,所有其他数据都传递给组件。 我试图根据从数据库带回的值呈现正确的组件,但遗憾的是它不起作用。 我是 Vue 新手,但它可以在 vue2 中工作,但希望它可以使用组合 API 在 Vue 3 中工作。

这是我要替换的组件代码:

<component :is="question.type" :propdata="question" />

在浏览器中查看时,这是实际显示的内容,但不使用 SelectInput 组件:

<selectinput :propdata="question"></selectinput>

SelectInput 是我的目录的一个组件,如果我对 :is 值进行硬编码,它就会按预期工作,如下所示:

<component :is="SelectInput" propdata="question" />

我的完整组件调用 component 组件并交换组件:

<template>
    <div class="item-group section-wrap">
        <div v-bind:key="question.guid" class='component-wrap'>
            <div class="component-container">
                <!-- working -->
                <component :is="SelectInput" :propData="question" />
                <!-- not working -->
                <component v-bind:is="question.type" :propData="question" />
            </div>
        </div>
    </div>
</template>

<script setup>

    import { defineProps, toRefs } from 'vue';

    import SelectInput from "./SelectInput";
    import TextareaInput from "./TextareaInput";

    const props = defineProps({
        question: Object,
    });

    const { question } = toRefs(props);

</script>

P粉779565855
P粉779565855

全部回复(2)
P粉388945432

如果您的组件文件名等于问题对象上的类型说明符,那么您可以动态导入它们以保存一些代码行。

这也会带来更好的可扩展性,因为如果您创建更多类型,您不必再接触此组件。



sssccc
P粉775788723

发现,因为我使用的是脚本设置,所以组件未命名,因此组件组件不知道要渲染哪个组件。

因此,我创建了一个包含组件的对象以及对该组件的引用:

const components = {
        'SelectInput': SelectInput,
        'TextareaInput': TextareaInput
    };

另一个函数接受我想要显示的组件并将其链接到实际组件:

const component_type = (type) => components[type];

然后在模板中我调用该函数并呈现正确的组件:

完整的固定代码:



sssccc

不太确定这是否是正确的方法,但它现在呈现正确的组件。

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!