Home > OS >  Why isn't a reactive variable watchable?
Why isn't a reactive variable watchable?

Time:06-25

I am developing a simple application in Vue3 and TypeScript. I defined an interface and initialized a reactive variable scrap that I the wanted to watch:

interface Scrap {
  Text: string,
  ModificationDate: string,
}
const scrap = ref<Scrap>({ Text: '', ModificationDate: '' } as Scrap)
watch(() => scrap, () => console.log('change'))

scrap.Text is modified in the application UI and I see these changes in DevTools → Vue.

The watch() callback is however not fired, despite that change. What is the reason for that?

I tried both watch(scrap, () => console.log('change')) and watch(() => scrap, () => console.log('change')) but there were no difference in behaviour (nor errors or warnings).

CodePudding user response:

In case the whole object is watched, it should be a deep watcher:

watch(scrap, () => console.log('change'), { deep: true })

Otherwise a specific property should be watched:

watch(() => scrap.value.Text, () => console.log('change'))
  • Related