說我有從資料庫中檢索到的物件串列,我正在通過腳本塊中的 foreach 回圈迭代它們
export default {
props: {
guests: {
type: Object,
default: null,
},
...
},
computed: {
myGuests() {
this.guests.forEach(guest => {
// the if guest.age > than 18 condition should be here
const myGuests = JSON.parse(JSON.stringify(guest));
// body of my method
});
return ...;
},
},
我想對它做一個條件,所以如果年齡大于 18 我將它們存盤在另一個物件上,那么當我從模板塊呼叫該方法時,指令 v-for 應該通過這些元素(即年齡大于18(而不是遍歷所有不同年齡的客人))
v-for="(guest, g) in myGuests" //call for the new created object whose age property is > 18
:key="g"
...
uj5u.com熱心網友回復:
您可以在計算屬性中使用過濾器:
Vue.component('Child', {
template: `
<div>
<div v-for="(guest, g) in myGuests" :key="g">
{{ guest.name }} - {{ guest.age }}
</div>
</div>
`,
props: {
guests: {
type: Array,
default: null,
},
},
computed: {
myGuests() {
return this.guests.filter(g => g.age > 18)
}
}
})
new Vue({
el: '#demo',
data() {
return {
guests: [{'name': 'aa', 'age': 15}, {'name': 'bb', 'age': 21}, {'name': 'cc', 'age': 18}, {'name': 'dd', 'age': 19}, {'name': 'ee', 'age': 20}, {'name': 'ff', 'age': 24}]
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<child :guests="guests"> </child>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/434629.html
