简体   繁体   中英

Passing forEach loop data to href attribute in Vue

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?

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>

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