[英]How to use v-if, v-else inside of v-for properly in Vuejs?
[英]How to use v-else statment in the v-for loop in Vuejs?
computed: { status() { const box = this.box; const paint = this.paint; const matchingdata = this.matchingdata.filter( (m) => m.boxid == box.boxid && m.paintid == paint.paintid )[0]; }
<div v-for="paint in paints":key="paint.id" class="line"> <div v-if=" matchingdata.some( (m) => m.boxid == box.boxid && m.paintid == paint.paintid ) "> <StatusComponent:box="box":paint="paint":matchingdata="matchingdata" /> <,--only status like ok,not, medium to be printed on line accordingly --> </div> <div v-else>sa</div> //ITS NOT WORKING </div>
從循環中,我正在獲取數據。 我放置了v-if條件,如果有數據根據條件顯示內容。
而且我還想設置條件,如果沒有找到數據,我想顯示“沒有找到數據”。 為此,我采取了 v-else 條件。 但其他條件不起作用。
如果像上面那樣設置(v-else 語句),那么它會打印每個數據。 如何將條件設置為僅顯示數據,什么都不匹配?
您將需要另一個計算屬性來查找整個數據集中是否有任何匹配項。 然后像這樣使用該計算屬性:
<template v-if="anythingMatching">
...your current code...
</template>
<template v-else>
<div>sa</div>
</template>
當然,你可以使用<div>
代替<template>
您應該處理一些狀態以顯示相應的消息,您需要使用一些邏輯來檢測它們
然后使用計算的道具過濾掉你的結果,過濾后的副本就是你循環的內容,加上它將過濾后的項目與原始項目分開,這樣你就知道原始項目有項目。
例如,(沒有 StatusComponent 所以它只輸出 json)
<div id="app">
search <input v-model="filter.search"/>
box 1 <input type="radio" v-model="filter.box" :value="1">
box 2 <input type="radio" v-model="filter.box" :value="2">
<div v-if="!loading">
<template v-if="filtered_paints.length">
<div v-for="(paint, index) in filtered_paints" :key="paint.id" class="line">
{{ index }}:
{{ filter.search ? 'searched: ' + filter.search : '' }}
{{ filter.box ? 'in box: ' + filter.box : '' }}
{{ paint }}
</div>
</template>
<template v-else>
<div v-if="!paints.length">
There was an issue loading paints.
</div>
<div v-else>
No matching paints, for:
{{ filter.search ? filter.search : '' }}
{{ filter.box ? 'in box: ' + filter.box : '' }}
</div>
</template>
</div>
<div v-else>
Loading paints...
</div>
</div>
{
data() {
return {
loading: true,
filter: {
search: '',
box: 0
},
paints: [],
};
},
computed: {
filtered_paints() {
return this.paints.filter((i) => {
if (!this.filter.box && this.filter.search === '') {
return true
}
let found = false
if (this.filter.box && this.filter.search) {
if (i.boxid === Number(this.filter.box) && i.name.startsWith(this.filter.search)) {
found = true
}
return found
}
if (this.filter.box && i.boxid === Number(this.filter.box)) {
found = true
}
if (this.filter.search && i.name.startsWith(this.filter.search)) {
found = true
}
return found
})
}
},
mounted() {
console.log('Mock loading some paints');
setTimeout(() => {
this.paints = [
{ id: 1, paintid: 1, boxid: 1, name: 'white' },
{ id: 2, paintid: 2, boxid: 2, name: 'black' }
]
this.loading = false
}, 2000)
}
}
在線查看示例: https://playcode.io/849492/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.