[Vuejs]-Invalid watch source: "$route" vuejs

6👍

Reactivity of $route is lost when the reactive context object is destructured (as explained in @vue/composition-api Issue #264). The watch method must keep a reference to the reactive object to maintain its reactivity:

export default {
  // DON'T DO THIS
  // setup(props, { root: { $route } }) {     // reactivity lost!

  // DON'T DO THIS
  // setup(props, context) {
  //   const { root: { $route } } = context   // reactivity lost!    
  // }

  setup(props, context) {
    // reactive!
    watch(() => context.root.$route, () => dataGet())
  }
}

demo

Verified with @vue/composition-api 1.0.0-beta.11 and Vue 2.6.11

👤tony19

2👍

You need to give watch an object, then name the thing being watched as a key to that object. So:

watch: {
  $route(to, from) {
  // react to route changes...
  }
}

See here: https://router.vuejs.org/guide/essentials/dynamic-matching.html#reacting-to-params-changes

👤powlo

0👍

I almost had the same problem and when I wanted to check the root change and desert root change it was having a problem. To fix this problem, you can use the following code:

Eager Watchers

watch(source, (newValue, oldValue) => {
  // executed immediately, then again when `source` changes
}, { immediate: true })

For example:

watch(
    () => route.query,
    () => {
      console.log(route.query)
    },
    { immediate: true }
)

Leave a comment