我试图总结一个对象中的几个属性。
我使用 VueJS 过滤器,结合 ES5 reduce 函数将数字相加得到总数。
嗯,目前还不起作用。有人愿意帮我吗?
new Vue({
el: '.app',
data: {
products: [{
"pid": "37",
"pname": "Reprehenderit",
"price": "4.29",
"amount": "1"
}, {
"pid": "45",
"pname": "Sit",
"price": "1.00",
"amount": "4"
}, {
"pid": "67",
"pname": "Omnis",
"price": "7.00",
"amount": "2"
}],
}
});
Vue.filter('subtotal', function (list, key1, key2) {
return list.reduce(function(total, item) {
return total + item.key1 * item.key2
}, 0)
})
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>
<div class="app">
Product example: {{ products[0].pname }}
<br><br>
Total: {{ products | subtotal 'price' 'amount' }}
</div>
看起来你的事件处理程序正在 vue 构建之后初始化。如果您的事件在调用时未附加,它们将被忽略。
另外,你不能像这样引用你的对象属性product.variable
你需要使用product[variable]
Vue.filter('subtotal', function (list, key1, key2) {
return list.reduce(function(total, item) {
return total + item[key1] * item[key2]
}, 0)
})
new Vue({
el: '.app',
data: {
products: [{
"pid": "37",
"pname": "Reprehenderit",
"price": "4.29",
"amount": "1"
}, {
"pid": "45",
"pname": "Sit",
"price": "1.00",
"amount": "4"
}, {
"pid": "67",
"pname": "Omnis",
"price": "7.00",
"amount": "2"
}],
}
});
<script src="http://cdnjs.cloudflare.com/ajax/libs/vue/1.0.11/vue.min.js"></script>
<div class="app">
Product example: {{ products[0].pname }}
<br><br>
Total: {{ products | subtotal 'price' 'amount' }}
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)