Search code examples
javascriptvue.jsobjectvuejs2v-for

Vue: Setting initial data string with link


I have an array of objects as boxData in my initial data. How would I go about making the word "here" a hyperlink that I can use whenever referencing boxData?

data() {
    return {
        boxData: [
            {
                body: "This is the link here."
            },
            {
                body: "Normal text."
            }
        ]
    }
}

Child component

<div v-for="(box, index) in boxData" class="box">
    <div>
         {{ box.body }}
    </div>
</div>

Solution

  • Ideally, the objects with a link would have a property like url. Then, assuming all of the links should say "This is the link here", you could do:

    <div v-for="(box, index) in boxData" class="box">
      <div>
        <template v-if="box.url">
          This is the link <a :href="box.url">here</a>.
        </template>
        <template v-else>
          {{ box.body }}
        </template>
      </div>
    </div>
    

    Then you don't need "This is the link here" in any of the objects.