skr
skr

Reputation: 1801

Vue how to watch inner values of json data

I have 'd' array in data and I want to watch if its elements gets changed, but some of the elements are nested.

My example is basically if I change the value Apple to Axe watcher should execute the methods inside of it, How do I achieve it?

 <template>
  <div>
    <button @click="change">Click me</button>
    {{ d }}
  </div>
</template>

<script>
export default {
  watch: {
    d: function() {
      this.hello();
    },
  },
  data() {
    return {
      d: [{ a: 'apple' }, { b: 'bananana' }, 'c'],
    };
  },
  methods: {
    hello() {
      alert('Executed');
    },
    change() {
      this.d[0].a = 'axe';
    },
  },
};
</script>

<style></style>

Upvotes: 0

Views: 659

Answers (1)

Owl
Owl

Reputation: 6853

Use deep: true on your watcher

watch: {
    d: {
      handler(val) {
        this.hello();
      },
      deep: true
    }
  },

Upvotes: 2

Related Questions