v-if
也常搭配 Array 筆數決定是否 Render HTML。
Version
Vue 3.4
Composition API
<template>
<ul>
<li v-for="(item, i) in companies" :key="i">
<span>{{ item.name }}</span>
<span>{{ item.product }}</span>
<span>{{ item.price }}</span>
</li>
</ul>
<button v-if="companies.length">Next</button>
</template>
<script setup>
import { ref } from 'vue'
let companies = ref([
{ name: 'Apple', product: 'MacBook', price: 100 },
{ name: 'Google', product: 'Android', price: 200 },
{ name: 'Microsoft', product: 'Windows', price: 300 }
])
</script>
Line 15
let companies = ref([
{ name: 'Apple', product: 'MacBook', price: 100 },
{ name: 'Google', product: 'Android', price: 200 },
{ name: 'Microsoft', product: 'Windows', price: 300 }
])
companies
state 以 Array 形式儲存
Line 2
<ul>
<li v-for="(item, i) in companies" :key="i">
<span>{{ item.name }}</span>
<span>{{ item.product }}</span>
<span>{{ item.price }}</span>
</li>
</ul>
- v-for:使用
v-for
搭配<ul>
與<li>
列舉 Array
Line 9
<button v-if="companies.length">Next</button>
- v-if:若 Array 非空則顯示,反則隱藏
因為 JavaScript 有 falsy value 傳統,所以 length 非 0 為
true
,0 為false
Options API
<template>
<ul>
<li v-for="(item, i) in companies" :key="i">
<span>{{ item.name }}</span>
<span>{{ item.product }}</span>
<span>{{ item.price }}</span>
</li>
</ul>
<button v-if="companies.length">Next</button>
</template>
<script>
export default {
data: () => ({
companies: [
{ name: 'Apple', product: 'MacBook', price: 100 },
{ name: 'Google', product: 'Android', price: 200 },
{ name: 'Microsoft', product: 'Windows', price: 300 }
]
})
}
</script>
- 最後附上相同功能的 Options API 供參考
- State 宣告在
data()
function v-if
使用上不變
Conclusion
v-if
常搭配 JavaScript 的 falsy value 使用,最典型就是 Array 的 length