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?

4
  • Can't you just import watch method from vue package and run it on your router? watch(route.query), like in any composables? Commented Jun 22, 2022 at 7:33
  • No because I want to watch in my .js plugin file; not within a component. Commented Jun 22, 2022 at 7:44
  • watch can watch any object. Did you try watching this.$router.currentRoute ? Commented Jun 22, 2022 at 8:11
  • I know, but where is $watch in my Vue instance (So not in my components) Commented Jun 22, 2022 at 8:13

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.