3 回答
TA贡献1155条经验 获得超0个赞
你想使用 v-for 循环来渲染 div,并写一次条件:
模板:
<template v-for="(value, index) in fetch">
<div v-if="value > 0" >
<p> DIV {{ index + 1 }} </p>
</div>
</template>
如果要使用数组的一部分,从 X 索引开始到 X+Y 索引结束,请使用 array.splice 并迭代新数组(从索引 1 开始并获取以下 3 个索引):
let filteredFetch = fetch.splice(1, 4);
模板:
<template v-for="(value, index) in filteredFetch">
<div v-if="value > 0" >
<p> DIV {{ index + 1 }} </p>
</div>
</template>
TA贡献1859条经验 获得超6个赞
解耦的方法是控制数据——在这种情况下不要弄乱v-ifs,使用计算属性(或方法,如果你需要比这更复杂的话):
new Vue({
el: "#app",
data: {
nextNumber: null,
fetch: []
},
computed: {
filteredFetch3() {
// the v-if is solved here with a filter
return this.fetch.filter(e => e > 3)
},
filteredFetch5() {
// the v-if is solved here with a filter
return this.fetch.filter(e => e > 5)
}
},
methods: {
pushNumber() {
this.fetch.push(Number(this.nextNumber))
this.nextNumber = null
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<label for="numberInput">
Number input: <input id="numberInput" v-model="nextNumber" /><button @click="pushNumber">ADD NUMBER TO FETCH LIST</button>
</label>
<hr /> FETCH (ALL THE FETCHED NUMBERS APPEAR HERE):
<br /> {{ fetch }}
<hr /> ONLY NUMBERS ABOVE 3 WILL APPEAR IN THIS LIST:
<ul>
<li v-for="(number, i) in filteredFetch3" :key="`${ number }-${i}`">
{{ number }}
</li>
</ul>
<hr /> ONLY NUMBERS ABOVE 5 WILL APPEAR IN THIS LIST:
<ul>
<li v-for="(number, j) in filteredFetch5" :key="`${ number }-${j}`">
{{ number }}
</li>
</ul>
</div>
TA贡献1886条经验 获得超2个赞
我不知道这是你想要实现的,但这是我的理解,请检查 jsfiddle 中的这段代码以及它的外观:
new Vue({
el: "#app",
mounted(){
var totalBoxes = 10;
for(let b=0; b < totalBoxes; b++){
var replyDataObj1 = b;
replyDataObj1={
"route_id" : b
}
this.toListFetch= replyDataObj1; /** this will collect all the data from fetch as a list **/
this.fetch.push(this.toListFetch); /** list from toListFetch will be pushed to this.fetch **/
}
},
data() {
return {
fetch:[],
toListFetch: ''
}
},
computed: {
filteredBoxes() {
// Computed property to return only fecth where route_id is greater than 0
return this.fetch.filter(f => f["route_id"] > 0);
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<p>
Filtered boxes
</p>
<div v-for="(f, indexFiltered) in filteredBoxes" :key="indexFiltered">
DIV {{ f.route_id }}
</div>
</div>
计算属性非常适合从数据属性中的项目中查找或过滤
添加回答
举报