2017-05-26 70 views
0

我正在用vue.js做一个简单的待办事项列表。我试图将所有price总和在一个数组中。要做到这一点我写了一个小函数内部computed, 但出了问题,这是我jsVue.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; 
    } 
    } 
}); 

存在被打破了功能forEach里面的东西,任何人都知道为什么吗?

+0

您是否尝试过一个简单的for循环看到的结果? –

+0

是的,但我想看到forEach –

回答

5

,你传递给forEach回调函数里面,this确实n要指向组件,它是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; 
} 

一般来说,我不会用的forEach,我会用reduce。它成为了一个漂亮的单行箭头共同发挥作用:

totale: function() { 
    return this.todos.reduce((sum, todo) => sum + todo.price, 0) 
} 
+0

'this.todos'没有任何价格属性 – rishipuri

+1

是的,发现我的错误一秒钟后,纠正它。 –

+0

非常有用,谢谢! –

0

替换代码

this.todos.forEach(function(){ 
    total += this.todos.price 
    }); 

this.todos.forEach(function(data){ 
    total += data.price 
    }); 
+0

请再次检查我的代码。 –

+0

现在应该工作(删除我的旧评论)。 –