简体   繁体   中英

Vue 3 - Composition API - Dynamically add template with text interpolation

I have a Component that take a string property, like this:

<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>

Whenever the property contains text I would like to add a " <p> {{transcription}} </p> " to the template that displays the text and changes based on the property content. The append must be dynamic. Any suggestions will be appreciated

Try to use a computed property:

<script lang="ts" setup>

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

</script>

Build an array of transcriptions, like:

<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>

And use v-for in your template:

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

Be aware that the key should be unique, which may not be the case in the example above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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