Pds*_*Ink 0 javascript foreach vue.js
我正在练习一个简单的待办事项清单vue.js.我试图price在数组中加总.要做到这一点,我在里面写了一个小函数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;
}
}
});
Run Code Online (Sandbox Code Playgroud)
内部有一些东西forEach打破了这个功能,有谁知道为什么?
在您传递给的回调函数中forEach,thisnto指向组件,undefined默认情况下是.
https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
回调函数接收每个todo作为参数,因此示例如下所示:
totale: function(){
var total = 0;
this.todos.forEach(function (todo) {
total += todo.price
});
return total;
}
Run Code Online (Sandbox Code Playgroud)
一般来说,我不会使用forEach,我会使用reduce.与箭头功能一起,它成为一个很好的单行:
totale: function () {
return this.todos.reduce((sum, todo) => sum + todo.price, 0)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
272 次 |
| 最近记录: |