2016-08-03 195 views
5

我需要檢查變量rasters_previews_list的變化。這裏是我的代碼:觀察變量變化不起作用

var userContent = Vue.extend({ 
    template: '<p>Some template</p>', 
    data: function() { 
    return { 
     rasters_previews_list: [] 
    } 
    }, 
    watch: { 
    'rasters_previews_list': function(value, mutation) { 
     console.log("Value changed");  
    } 
    } 
}); 

但是在控制檯我沒有看到Value changed當它有新的數據。

數據變更功能:

map.on('draw:created', function (e) { 
//... 

    Vue.http.post('/dbdata', DataBody).then((response) => { 
     userContent.rasters_previews_list = response; // putting JSON answer to Component data in userContent 

     console.log(response); 


     }, (response) => { 
      console.log("Can't get list rasters metadata from DB. Server error: ", response.status) 
     }); 

我改變map.on('draw:created', function (e)(單張JS)值。我看到console.log輸出,所以似乎數據正在改變。

+0

也提到你永遠改變你的代碼 – gurghet

+0

@gurghet值我從外面 –

+0

更改數據你有過成功與提供答案? – gurghet

回答

4

如果你想改變一個數組的值,你必須使用特殊的數組擴展方法Vue.setVue.delete

Due to limitations of JavaScript, Vue cannot detect the following changes to an Array:

  • When you directly set an item with the index, e.g. vm.items[0] = {} ;

  • When you modify the length of the Array, e.g. vm.items.length = 0 .

https://vuejs.org/api/#Vue-set

這個問題在common gotchas

When you modify an Array by directly setting an index (e.g. arr[0] = val) or modifying its length property. Similarly, Vue.js cannot pickup these changes. Always modify arrays by using an Array instance method, or replacing it entirely. Vue provides a convenience method arr.$set(index, value) which is just syntax sugar for arr.splice(index, 1, value).

+0

如何在數據中的'Vue.extend'內添加'set'? –

+0

我建議你仔細閱讀文檔,因爲它在那裏有明確的解釋。無論如何,你不要在'Vue.extend'中使用'set',你可以使用'set'來改變數組。在你發佈的代碼中,你並沒有改變數組。請顯示您要更改陣列的位置。 – gurghet

+0

我可以這樣做:'userContent。$ set('rasters_previews_list',response);'?這是價值在變化的部分。 我得到錯誤:'不能讀取屬性$ set'未定義' 我正在改變數組在字符串:'userContent.rasters_previews_list = response;' –