[Vuejs]-How to watch for prop changes when data masks prop?

0👍

You can’t have a same key in data/props/computed/whatever , keys must be different as they are intended to be assigned to the single this object


You may use Composition API watch in onMounted or setup or whatever hook:

import { watch } from 'vue'
export default defineComponent({
  data: () => ({ p: 123 }),
  props: ['p'],
  onMounted() {
    watch(() => this.$data.p, (v) => { console.log(v) })
  }
})

I’m not sure what the other object is named, maybe this.$setup, but you can use setup instead of data

import { watch, ref } from 'vue'
export default defineComponent({
  setup: () => {
    const p = ref(123);
    watch(p, (v) => console.log(v));
    return { p }
  },
  props: ['p'],
})

Setup hook is recommended to use instead of mixins as it allows to rename things easily

0👍

Since noone answered in two weeks I will write my answer I came up with:

It is possible to specify what type of property a watcher should watch (either prop or data) if both prop and data have the same name by providing the full name of the property as seen in the Vue component, as string.

So, to watch for a prop change, you would write:

watch: { "_props.p"() {} }

and to watch data you would write:

watch: { "_data.p"() {} }

Leave a comment