---
# System prepended metadata

title: v-for 循環內的 v-if（顯示個別組件
tags: [' Vue', Javascript]

---

---
tags: Javascript, Vue
---

# v-for 循環內的 v-if（顯示個別組件

盡量不要在`v-for`中使用`v-if`，因為當它們存在於同一節點上時，`v-if`具有比 更高的優先級`v-for`。
[查看文件詳細說明](https://vuejs.org/guide/essentials/list.html#v-for-with-v-if)

利用取得物件ID去判斷點擊的目標
```htmlmixed=
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<div id="app">
  <h2>Todos:</h2>
  <ol>
    <li v-for="todo in todos">
    <a v-on:click="toggle(todo)" href="javascript:;">【待辦事項】</a>
        <span v-if="isActive == todo.id">
          {{ todo.text }}
        </span>
    </li>
  </ol>
</div>
```
以下為Vue的程式碼
```javascript=
new Vue({
  el: "#app",
  data: {
    todos: [
      { id: 1, text: "Learn JavaScript"},
      { id: 2, text: "Learn Vue"},
      { id: 3, text: "Play around in JSFiddle"},
      { id: 4, text: "Build something awesome"}
    ],
    isActive: "false"
  },
  methods: {
    toggle: function (todo) {
      this.isActive = todo.id;
    },
  }
})
```
codepen範例
<iframe height="300" style="width: 100%;" scrolling="no" title="v-for 循環內的 v-if（顯示個別組件）" src="https://codepen.io/joe94113/embed/preview/vYeYdJK?default-tab=html%2Cresult" frameborder="no" loading="lazy" allowtransparency="true" allowfullscreen="true">
  See the Pen <a href="https://codepen.io/joe94113/pen/vYeYdJK">
  v-for 循環內的 v-if（顯示個別組件）</a> by 王冠智 (<a href="https://codepen.io/joe94113">@joe94113</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>