0

I have a small package that was built in Vue2 that I'm trying to migrate to Vue3 now where a route is being watched programmatically by obtaining the App instance within vue-router and it's being watched like so:

function myPluginName(router) {
  router.app.$watch(`$route.query.${this.config.name}`, () => {
   // do stuff outside my vue instance
  });
}

And its being called within my Vue component like so:

myPluginName(this.$router);

In my Main JS I added the router to my Vue instance:

const app = createApp(App);
router.app = app;
app.use(router);

Which works fine and I can get the router.app as an instance. However in Vue2 you could add a $watch to your app instance and it would catch it for you; this doesn't seem to be the case with Vue3 since console.logging my Vue instance doesn't show any sign of $watch nor does it work.

So in short:

Is there still a way I can watch my Vue instance OUTSIDE my Vue instance?

Update:

It does work when I push my Vue instance into the router.app in my component:

this.$router.app = this
myPluginName(this.$router);

But that doesn't feel really fool-proof ish I guess?

CaptainCarl
  • 3,411
  • 6
  • 38
  • 71

1 Answers1

1

In Vue3, everything related to reactivity is out of any Vue instance. That means you can create a watcher without even having a Vue app:

import { watch } from 'vue'

export function myPlugin(route) {
  watch(route.query, (newQuery, oldQuery) => {
    // TODO
  })
}

There is no more a global $watch property on Vue instances.

Kapcash
  • 6,377
  • 2
  • 18
  • 40