3

I have an array that I'm looping over in Vue, and rendering an anchor element with each iteration. The array that i'm looping over is one of my props, I've tried several different things and while I do believe I could get it working, the way would seem very hacky to me and I'm wanting to make sure it's not simpler than I'm thinking

              <template v-for="(lead, index) in leads">
                 <a target="_blank" v-bind:href="lead.present_url"><b>foobar</b></a>
                 <div>{{lead.name}}</div>
                 <div>{{lead.id}}</div>
              </template>

I've tried all manner of combinations, the following is not a comprehensive list but just some examples of what I've tried: :href="lead.present_url" href='lead.present_url' :href='${lead.present_url}' (with tildas), several variations of these, including with and without v-bind, v-bind:href='leads[index].present_url'

  props: {
    leads: Array
  },

My question is: what is the best way to go about doing this?

1 Answer 1

1

You actually want to use v-for on the element that you want multiple of, and you need to bind a :key as well:

<template>
<div class="lead-container">
  <div v-for="lead in leads" :key="lead.id">
    <a target="_blank" :href="lead.present_url">
      <strong>foobar</strong>
    </a>
    <div>{{lead.name}}</div>
    <div>{{lead.id}}</div>
  </div>
</div>
</template>

<script>
export default {
  props: {
    leads: {
      type: Array,
      default: () => [],
    }
  }
}
</script>
Sign up to request clarification or add additional context in comments.

3 Comments

My mistake, there's actually quite a few other element in between the template tags that I removed for the sake of cleanliness but the anchor tag is one of them.
Answer updated - same concept. You need some sort of container for each lead aside from the template. While the template can use v-for, it's kind of weird because then each element inside the template would need a :key binding, since the template is not an element in the DOM.
Also, the <b> tag is deprecated. Use either <strong> or a class that defines font-weight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.