[英]Vue.js computed function return nothing
I'm practicing with a simple to-do list with vue.js
. 我正在使用
vue.js
一个简单的待办事项清单。 I'm trying to sum all price
within an array. 我试图对数组中的所有
price
求和。 To do that I wrote a little function inside computed
, but something has gone wrong, here is my js
: 为此,我在
computed
内部编写了一个小函数,但是出了点问题,这是我的js
:
var app= new Vue({
el: "#app",
data: {
message: "Lista della spesa",
seen: true,
todos: [
{msg: 'prezzemolo', price: 10},
{msg: 'pomodori', price: 20},
{msg: 'zucchine', price: 5}
],
},
methods: {
addToDo: function() {
if(this.nome && this.prezzo) {
this.todos.push({msg: this.nome, price: this.prezzo});
}
this.nome = "";
this.prezzo = "";
},
RemoveThis: function(index) {
this.todos.splice(index,1);
}
},
computed: {
totale: function() {
var total = 0;
this.todos.forEach(function() {
total += this.todos.price
});
return total;
}
}
});
There is something inside the forEach
that is breaking the function, anyone know why? forEach
内部有某些东西破坏了功能,有人知道为什么吗?
inside the callback function that you passed to forEach
, this
does nto point to the component, it is undefined
by default. 在传递给
forEach
的回调函数中, this
确实指向该组件,默认情况下undefined
。
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
the callback function receives each todo
as the argument, so an example would look like this: 回调函数接收每个
todo
作为参数,因此示例如下所示:
totale: function(){
var total = 0;
this.todos.forEach(function (todo) {
total += todo.price
});
return total;
}
Generally, I would not use forEach, I would use reduce . 通常,我不会使用forEach,而会使用reduce 。 Together with an arrow function it becomes a nice one-liner:
结合箭头功能,它成为了一个不错的选择:
totale: function () {
return this.todos.reduce((sum, todo) => sum + todo.price, 0)
}
Wrong use of forEach
错误使用
forEach
eg 例如
var total = 0; var arrayOfObjects = [{price: 10},{price: 20},{price : 30}]; // Correct usage: arrayOfObjects.forEach(function(obj) { total += obj.price; }) console.log(total)
Refer to: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=control 请参阅: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach?v=control
Replace code 替换代码
this.todos.forEach(function(){
total += this.todos.price
});
to 至
this.todos.forEach(function(data){
total += data.price
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.