【问题标题】:vue3 js component :is not changing componentvue3 js组件:不改变组件
【发布时间】:2022-06-10 23:02:17
【问题描述】:

我有一个从 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>

【问题讨论】:

  • question.type的值是多少?
  • {{ question.type }}检查question.type的值。

标签: vue.js vuejs3 vue-composition-api


【解决方案1】:

发现因为我使用的是script setup,所以组件没有命名,所以component 组件不知道要渲染哪个组件。

所以,我创建了一个包含组件的对象和对该组件的引用:

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

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

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

然后在模板中调用函数并渲染正确的组件:

<component v-bind:is="component_type(question.type)" :propData="question" />

完整的固定代码:

<template>
    <div class="item-group section-wrap">
        <div v-bind:key="question.guid" class='component-wrap'>
            <div class="component-container">
                <!-- working -->
                <component v-bind:is="component_type(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 components = {
        'SelectInput': SelectInput,
        'TextareaInput': TextareaInput
    };

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

    const { question } = toRefs(props);

</script>

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-03
    • 2021-05-22
    • 1970-01-01
    • 2021-08-15
    • 2022-11-09
    • 2021-05-28
    • 2022-10-14
    相关资源
    最近更新 更多