Search code examples
javascriptvue.jsvuejs3watchprop

Vue 3 - Watching prop stops working after emitting to parent


I have an issue trying to watch a prop in a child component. Here's a playground link with a a little code to reproduce the issue:

Vue SFC Playground

The child component (in orange) inherits the data from the parent (just an array). The child component copies the data from the parent whenever it changes, and you can then modify (append) to the child data, and when you click save, the data should be emitted into the parent (and is then subsequently passed into the child as a prop).

The problem is, as soon as you click save in the child component, the child is no longer able to watch for changes to the prop. It never sees the future changes from the parent. Vue devtools correctly sees the data though. What am i missing here?


Solution

  • The watch composable accepts either a 'ref', 'reactive' object, or a getter function.

    But as stated in the documentation, it doesn't accept inner property of a reactive object:

    Do note that you can't watch a property of a reactive object like this:

    const obj = reactive({ count: 0 })
    // this won't work because we are passing a number to watch()
    watch(obj.count, (count) => {
     console.log(`count is: ${count}`)
    })
    

    So to listen to props.list changes, you need to use a getter function:

    watch(() => props.list, () => {
      // ...
    })
    

    See this working playground