【发布时间】:2019-01-03 17:35:26
【问题描述】:
我正在从这个小例子开始我在 vue 中的第一步。我正在尝试根据提供的数据来实现项目总和。 (完整的例子可以在this jsffile找到)
组件:
Vue.component('items-table', {
props: ['items', 'item', 'total'],
template: `
<div>
<table>
<thead>
<tr>
<th>Description</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<tr
v-for="item of items"
v-bind:key="item.id"
>
<td>{{item.desc}}</td>
<td class="price">{{item.price}}</td>
</tr>
</tbody>
</table>
<div>Total items: {{items.length}}</div>
<div>Total price: {{total}}</div>
</div>
`
});
在下面的应用程序中,控制台打印一个空数组,结果总是返回 0:
new Vue({
el: '#app',
data:{
items: []
},
computed: {
total: function(){
console.log(this.items);
return this.items.reduce(function(total, item){
return total + item.price;
},0);
}
},
mounted() {
console.log('app mounted');
}
});
最后,我提供将用于显示、操作和进行一些计算的初始数据:
<div id="app">
<items-table v-bind:total="total" v-bind:items="[
{ id: 1, desc: 'Banana', price: 10 },
{ id: 2, desc: 'Pen', price: 5 },
{ id: 3, desc: 'Melon', price: 5 }
]"></items-table>
</div>
我的问题是 {{total}} 中的价格总和始终为 0。看起来 items 数组在通过 v-bind:items 提供时从未设置(它不是反应式的吗?)。提前感谢您的帮助。
编辑:背景
将用于组件的所有数据都来自 PHP 纯文件。 CRUD 操作尚不可用。说可以直接从标签绑定数据非常重要。
【问题讨论】:
-
只需从组件中删除
data并迭代items道具 -
这是否按预期工作?
fiddle -
总计算值应该是items-table组件的一部分,而不是父组件。 items-table 应该有一个 items 道具,它会遍历它的内容。总计算值将引用 this.items 来计算总和。
-
computed将您的本地物品算作道具 -
@TheReason 说,在组件内部使用计算,如this fiddle
标签: javascript vue.js vuejs2 vue-component