2017-08-03 240 views
0

我需要获取数组内部的对象属性更改。 为了做到这一点,我使用了vue。$ watch。 我阅读文档,但我没有得到。

的情况是:

... 
data() { 
     return {    
      Questions: [{foo: 1}, {foo: 2}, {foo: 3}] 
     } 
    }, 
... 

this.$watch("Questions", function (newVal, oldVal) { 
    // something... 
}, { deep: true }); 

更新过的

的解决方案就在这里!

See the example on JsFiddle

+0

我不知道要明白什么是不是与你的jsfiddle –

回答

1

有是Javascript限制 - 如果改变阵列元件直接地(例如this.array[0].foo = 'bar'),Vue公司不能跟踪这些变化,因此,观察者将不被触发。

它会被触发,虽然如果你使用Array.prototype函数中的任何一个,比如push,pop或者会重新分配数组。

所以最根本的解决方案看起来是这样的:

change: function() { 
    let questions = this.Questions; 
    questions[0].foo = 5; 

    this.Questions = questions; 

    /* or 
    let index = 0; 
    let question = this.Questions[index]; 
    question.foo = 5; 
    this.Questions.splice(index, 1, question); 
    */ 
} 

更新的jsfiddle:here

东西看看:Arrays reactivity in Vue.js

+0

谢谢@yev。尽管该示例在** change **方法上进行了更改,但我需要该代码与双向绑定一起工作。我刚刚找到了解决方法,我会更新示例。但是,即使如此,我会给你一个赞成! :) –