Home  >  Q&A  >  body text

Unable to use router.push and unplugin-vue-router dependencies in Vue 3

I'm trying to migrate a Vue 2 project to Vue 3, in the Vue 3 project it has a library called "unplugin-vue-router", which is an automatic file-based routing in Vue that supports TS. But there are the following methods in the previous vue 2 (vue-router) login page:

created() {
     if (this.loggedIn) {
        this.$router.push('/projects');
     }
}

So I tried rewriting it in Vue 3:

onMounted(() => {
  if (loggedIn) {
    router.push('/projects');
  }
});

But it shows error: Cannot find name "router".ts(2304)

So my question is how to rewrite it and make it work with vue 3 and where can I change the configuration of unplugin-vue-router.

P粉864594965P粉864594965277 days ago481

reply all(1)I'll reply

  • P粉155832941

    P粉1558329412024-01-17 09:13:08

    In composition-api router, it is imported from the vue-router plug-in.

    In order to use it, you need to declare it as follows

    import { userouter } from "vue-router";
    
    const router = useRouter();
    onMounted(() => {
      if (loggedIn) {
        router.push('/projects');
      }
    });
    
    

    See vue-router for more details.

    reply
    0
  • Cancelreply