Home > database >  Vue 3 - Composition API - Dynamically add template with text interpolation
Vue 3 - Composition API - Dynamically add template with text interpolation

Time:10-06

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

CodePudding user response:

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>

CodePudding user response:

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.

  • Related