vue.js数据在递增时不更新

时间:2017-01-02 03:32:38

标签: javascript html vue.js

我有一个包含数组的对象,在完成一些逻辑后会增加。

Vue.js似乎没有捕获此增量并将其显示在视图中。

HTML:

<div id="demo">
  <p>{{points}}</p>
</div>

JS:

function Board()
{ 
  this.team1 = {pointsMade:[0]};
}

var newBoard = new Board();

newBoard.team1.pointsMade[0]++


new Vue({
  el: '#demo',
  data: {
    points: newBoard.team1.pointsMade
  }
})

setTimeout(newBoard.team1.pointsMade[0]++,1000)

我有JSFiddle概述了问题。

您可以看到setTimeout(newBoard.team1.pointsMade[0]++,1000)运行后,该值应为“2”,但仅显示为“1”。我在这里缺少什么?

1 个答案:

答案 0 :(得分:3)

定义时

  data: {
    points: newBoard.team1.pointsMade[0]
  }

points变量刚刚被赋予newBoard.team1.pointsMade[0]的当前值,此时此为1。这里没有魔力。 JS原语按值而不是通过引用工作。

因此,在更新newBoard.team1.pointsMade[0]变量后,point变量当然不会更新。

要使其工作,请使用object而不是原始值。对象在JS中通过引用工作。

来自Properties and Methods示例:

var data = { a: 1 }
var vm = new Vue({
  data: data
})
vm.a === data.a // -> true
// setting the property also affects original data
vm.a = 2
data.a // -> 2
// ... and vice-versa
data.a = 3
vm.a // -> 3

修改

此处还有另一个caveat

由于JavaScript的限制,Vue无法检测何时直接使用索引设置项目,例如vm.items[indexOfItem] = newValue。因此,请使用Vue.set(newBoard.team1.pointsMade, 0, newBoard.team1.pointsMade[0] + 1);

我更新了您的fiddle