首页 > 解决方案 > 在 vue.js 中访问 v-for 列表项对象数据

问题描述

<div v-for="deck in decks" :key="deck._id" slot="content">
  <div class="level">
    <div class="level-left">
      <div>
        <p>{{ deck._id }}</p>
        <p class="has-text-weight-semibold">{{ deck.title }}</p>
        <p>Boards: {{ deck.board1 }}</p>
        <p>Primary color: {{ deck.board1Color }}</p>
        <p>
          L/W/H: {{ deck.deckLength }}ft, {{ deck.deckWidth }}ft,
          {{ deck.deckHeight }}ft
        </p>
      </div>
    </div>
    <div class="level-right">
      <form @submit.prevent="deleteDeck">
        <button type="submit" class="button">Delete</button>
      </form>
    </div>
  </div>

  <br />
</div>

我可以在 v-for 循环中访问此对象的 id,但不能在删除按钮调用的方法中访问。

methods: {
    deleteDeck() {
      const deckId = this.deck._id;
      alert(deckId);
    }
}

这个单独的卡片组的 id 将被传递到 axios 删除请求中,但现在我只是想弄清楚如何访问它。this.id 包含该对象所属的较大对象的 id。

标签: javascriptvue.jsfrontendvue-component

解决方案


您所要做的就是将id模板中的方法传递给该方法:

模板 HTML

...
<form @submit.prevent="deleteDeck(deck.id)">
  <button type="submit" class="button">Delete</button>
</form>

零件

methods: {
  deleteDeck (id) {
    alert(id)
  }
}

推荐阅读