다음 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] 삭제
몇 마디 만하겠습니다