我有一个名为的数组products
,其结构如下:
{
"_id": "150",
"name": "Milk",
"description": "Skimmed",
"price": "10",
"ratings": [
{
"email": "[email protected]",
"rating": "5"
},
{
"email": "[email protected]",
"rating": "3"
},
{
"email": "[email protected]",
"rating": "1"
},
]
},
{
"_id": "151",
...
...
...
我想使用Vue.js计算产品的平均评分并将其显示在页面加载中。
我的产品HTML页面有一个,v-for = "(product, key) in products"
我可以使用它按名称,描述等显示所有产品。
任何帮助将不胜感激。提前致谢。
你可以试试:
new Vue({
el: '#app',
data() {
return {
products: [
{
"_id": "150",
"name": "Milk",
"description": "Skimmed",
"price": "10",
"ratings": [
{
"email": "[email protected]",
"rating": "5"
},
{
"email": "[email protected]",
"rating": "3"
},
{
"email": "[email protected]",
"rating": "1"
},
]
}
]
}
},
mounted () {
// mapping each item of products to merge averageRating calculated
this.products = this.products.map(product => {
// ratings summation
const totalRatings = product.ratings.reduce((acc, { rating }) => acc += Number(rating), 0)
const averageRating = totalRatings/product.ratings.length
// returning the merge of the current product with averageRating
return {...product, averageRating}
})
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>
<div id="app">
<ul>
<li v-for = "(product, key) in products" :key="key">
name: {{ product.name }} ~ averageRating: {{ product.averageRating }}
</li>
</ul>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句