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

我有一個從 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

如果您的元件檔案名稱等於問題物件上的類型說明符,那麼您可以動態匯入它們以保存一些程式碼行。

這也會帶來更好的可擴充性,因為如果您建立更多類型,您不必再接觸此元件。



P粉775788723

發現,因為我使用的是腳本設定,所以元件未命名,因此元件元件不知道要渲染哪個元件。

因此,我創建了一個包含元件的物件以及對該元件的引用:

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

另一個函數接受我想要顯示的元件並將其連結到實際元件:

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

然後在模板中我呼叫該函數並呈現正確的元件:

#完整的固定程式碼:



不太確定這是否是正確的方法,但它現在呈現正確的元件。

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!