[Vuejs]-Why Vue can't watch the data change?

0๐Ÿ‘

โœ…

in case of tableRowName contain objects then you have to use

deep:true

watch: {
        tableRowName(newtable,oldtable){
            console.log(1)
            createComparation()
        },
        immediate:true,
        deep: true,
        stockName(){
            changeTip()
        },
        
    },

but i think you are updating the array without reactive manner, Vue cannot detect the following changes to an array:

When you directly set an item with the index, e.g.

vm.items[indexOfItem] = newValue

When you modify the length of the array, e.g.

vm.items.length = newLength

var vm = new Vue({
  data: {
    items: ['a', 'b', 'c']
  }
})
vm.items[1] = 'x' // is NOT reactive
vm.items.length = 2 // is NOT reactive

0๐Ÿ‘

I guess whatching array might be the issue. You can try this:

computed: {
    rowNames() {
        return this.tableRowName;
        // if the line above doesn't work:
        return this.tableRowName.join();
    }
},
watch: {
    rowNames(newtable,oldtable){
        createComparation()
    },

0๐Ÿ‘

I think this is what youโ€™re looking for. You need to define the handler as an object for the property youโ€™re trying to watch and set immediate: true.

Vue.config.productionTip = false
Vue.config.devtools = false

new Vue({
  el: "#app",
  data() {
    return {
      tableRow: 0,
      tableRowName: [],
      stockName: [],
      rectWidth: 40,
      rectHeight: 5,
    }
  },
  watch: {
    tableRowName: {
      handler(newtable) {
        console.log('Calling createComparation function');
        console.info(newtable);
      },
      immediate: true
    }

  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button @click="tableRowName.push(Math.random())">Trigger change manually again</button>
</div>

0๐Ÿ‘

The watch method definition is wrong. When you need to use immediate, you have to put you function body into handler property.

For example,

 watch: {
  tableRowName: {
    handler: function() {

    },
    immediate: true
  }
        
  },

Leave a comment