Vue v-for 與 v-if 搭配使用

前言

在 Vue.js 中,v-forv-if 是兩個常用的指令,它們各自有著重要的功能。當我們將這兩者搭配使用時,可以實現更加動態和靈活的 UI。不過,直接在 v-for 中使用 v-if 會導致錯誤。這篇文章將探討這兩個指令如何搭配使用的場景,並提供解決方法。

錯誤範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<template>
<ul>
<li v-for="task in tasks" :key="task.id" v-if="!task.completed">
{{ task.name }}
</li>
</ul>
</template>

<script>
export default {
data() {
return {
tasks: [
{ id: 1, name: '任務 1', completed: false },
{ id: 2, name: '任務 2', completed: true },
{ id: 3, name: '任務 3', completed: false },
],
};
},
};
</script>

此範例會出現以下錯誤:

1
The 'XXXXX' variable inside 'v-for' directive should be replaced with a computed property that returns filtered array instead. You should not mix 'v-for' with 'v-if'

這是因為 v-forv-if 的優先級不同,當它們同時存在於同一節點時,v-if 的優先級高於 v-for,使得 v-if 的條件無法訪問到 v-for 作用域內的變量別名。

正確範例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<template>
<div>
<h1>任務清單</h1>
<p>已完成清單</p>
<ul>
<template v-for="task in tasks">
<li v-if="task.completed" :key="task.id">
{{ task.name }}
</li>
</template>
</ul>
</div>
</template>

<script>
export default {
data() {
return {
tasks: [
{ id: 1, name: '任務 1', completed: false },
{ id: 2, name: '任務 2', completed: true },
{ id: 3, name: '任務 3', completed: false },
],
};
},
};
</script>

Use v-for with v-if

結論

v-forv-if 的搭配使用可以讓我們在 Vue.js 中靈活地構建條件渲染的列表。這不僅提升了應用的互動性和動態性,也增強了可讀性。在實際開發中,請考慮性能與可讀性,選擇最適合的方式來實現需求。