繁体   English   中英

Vue 3 - Composition API - 动态添加带有文本插值的模板

[英]Vue 3 - Composition API - Dynamically add template with text interpolation

我有一个带有字符串属性的组件,如下所示:

<script lang="ts" setup>

    const props = defineProps<{
        transcription?: string;
    }>();
    
     watch(() => props.transcription,
         (newTranscription) => {
             if (newTranscription) {
                 console.log(newTranscription);
                 // dynamically ad paragraph with text interpolation
                 // `<p> {{ newTranscription }} </p>`
             }
          }
     );

</script>
<template>
    <h1>Transcriptions</h1>
    ...here i want to append a paragraph every time transcription has text
</template>

每当属性包含文本时,我想向显示文本的模板添加一个“ <p> {{transcription}} </p> ”,并根据属性内容进行更改。 append 必须是动态的。 任何建议将不胜感激

尝试使用计算属性:

<script lang="ts" setup>

    const props = defineProps<{
        transcription?: string;
    }>();
    
   const newTranscription = computed(() => {
             if (props.transcription) {
                 return props.transcription + "some dynamic content"
             }
     );

</script>

构建一个转录数组,例如:

<script lang="ts" setup>
    const transcriptions = [];

    const props = defineProps<{
        trascription?: string;
    }>();
    
     watch(() => props.trascription,
         (newTranscription) => {
             if (newTranscription) {
                 console.log(newTranscription);
                 //dynamically ad paragraph with text interpolation
                 transcriptions.push(newTranscription);
             }
          }
     );

</script>

并在模板中使用v-for

<p v-for="transcr in transcriptions" :key="transcr">{{transcr}}</p>

请注意,密钥应该是唯一的,而在上面的示例中可能并非如此。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM