Vue how to watch inner values of json data

|▌冷眼眸甩不掉的悲伤 提交于 2021-01-29 20:30:12

问题


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>

回答1:


Use deep: true on your watcher

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


来源:https://stackoverflow.com/questions/61911167/vue-how-to-watch-inner-values-of-json-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!