Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly watch an object in Vue?

I am trying to use a Vue watcher on a computed object and it is not working at all. It works properly if it's just a string, but not if it's an object. I followed the Vue documentation but I am still getting nothing logged to the console when the object changes. The properties of the object and computed property are changing, as I have confirmed in Vue Tools. What am I doing wrong? Thanks

<v-btn small dark @click="test1.asdf = 'blah'">Test</v-btn>
    data() {
      return {
        test1: {},
      }
    },
    computed: {
      test() {
        return this.test1
      }
    },

    watch: {
      test: {
        handler: function(val, oldVal) {
          console.log(oldVal, val);
        },
        deep: true
      }
    }
like image 209
BadCoder Avatar asked Nov 08 '25 01:11

BadCoder


1 Answers

Try this code, its works fine

<template>
  <div id="app">
    {{ test1 }}
    <hr />
    <button @click="test1.asdf = 'blah'">Click</button>
  </div>
</template>

<script >
export default {
  data() {
    return {
      test1: { asdf: "HEY" },
    };
  },
  computed: {
    test() {
      return this.test1;
    },
  },

  watch: {
    test: {
      handler: function (val, oldVal) {
        console.log(oldVal, val);
      },
      deep: true,
    },
  },
};
</script>

I'd guess in your case you should add .native at end of your click event like this @click.native="test1.asdf = 'blah'"

like image 79
Mohammad Avatar answered Nov 12 '25 04:11

Mohammad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!