[英]vuex function - returns true or false based on object value
我有一個返回子對象的數據,如下所示,因此this.children
將返回如下:
{
"1": {
"firstName": "JJJ",
"lastName": "B",
"day": "1",
"month": "1",
"year": 2012,
"name": "JJJ B",
"dateOfBirth": "2012-01-01",
"age": 6,
"id": "1"
},
"2": {
"firstName": "KKK",
"lastName": "B",
"day": "2",
"month": "2",
"year": 2004,
"name": "KKK B",
"dateOfBirth": "2004-02-02",
"age": 14,
"id": "2"
},
"3": {
"firstName": "LLL",
"lastName": "B",
"day": "3",
"month": "3",
"year": 2017,
"name": "LLL B",
"dateOfBirth": "2017-03-03",
"age": 1,
"id": "3"
}
}
如果該列表中的孩子的年齡低於 3,我想創建一個返回 true 或 false 的函數。我對 vue 很陌生。 我了解在使用 v-for 時如何檢索年齡,但不確定在涉及檢查對象值時如何使用 vue 函數。
做就是了
<ul v-for="child in getChildrenUnder3 "><li>{{child.age<3}}</li></ul>
或者您可以使用計算屬性:
computed:{ getChildrenUnder3(){ let children3=[]; for(let i=0;i<Object.keys(this.childList).length;i++){ if(Object.values(this.childList)[i].age<3){ children3.push(Object.values(this.childList)[i]) } } return children3; } }
並像這樣渲染它:
<ul v-for="child in getChildrenUnder3 "><li>{{child.age}}</li></ul>
只需將函數放在模板中
<template>
<div v-for="child in children" :key="child.id">
{{child.firstName}} is less than three: {{child.age < 3 ? 'TRUE' : 'FALSE'}}
</div>
</template>
但是,如果您試圖找出是否每個孩子都小於 3,則可以使用計算值來檢索此數據
minAge
應該返回找到的最低年齡
computed: {
minAge() {
return Math.min(Object.keys(this.children).map(k => {
this.children[k].age;
}))
}
}
然后您可以使用它在您的模板中生成布爾值,例如{{minAge<3}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.