Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Watch for variable change do not work

Tags:

vue.js

I need to check variable rasters_previews_list for changing. Here is my code:

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");      
    }
  }
});

But In console I do not see Value changed when it got new data.

Data changing function:

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)
      });

I change value in map.on('draw:created', function (e) (Leaflet JS). I see console.log output, so seems data is changing.

like image 650
Dmitry Bubnenkov Avatar asked Aug 03 '16 08:08

Dmitry Bubnenkov


People also ask

What is a variable watch?

Any item of data within a program that a programmer wants to observe when debugging. Watch variables may be viewed while the program runs on its own, is stepped through instruction by instruction or when the program crashes. Setting watch variables is part of the debugging operation in a compiler.

How do you add variables to watch?

In the Locals window, right-click the Person variable and select Make Object ID. You should see a dollar sign ($) plus a number in the Locals window, which is the Object ID. Add the object ID to the Watch window by right-clicking the Object ID and selecting Add Watch.

How do you watch variables in Vue?

Vue Watch Getter Function Using this format, we can set the first argument in watch to a function, and use it to calculate something. After that, the calculated value then becomes watched. For example, the below code will add both x and y together, and watch for its change.


1 Answers

If you want to change the value of an array you will have to use the special Array extension methods Vue.set and Vue.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

This problem is also mentioned in the 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).

like image 114
gurghet Avatar answered Sep 30 '22 06:09

gurghet