Unable to use router.push in Vue 3 with unplugin-vue-router dependency

Viewed 45

I'm trying to migrate a Vue 2 project to Vue 3, in the Vue 3 project It has a library named "unplugin-vue-router" which is an Automatic file based Routing in Vue with TS support. But In the previous vue 2 (vue-router) login page It has the following method inside:

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

So I tried to rewrite this in Vue 3:

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

But It shows an error: Cannot find name 'router'.ts(2304)

So my question is how to rewrite this and make It works with vue 3, and where I can change the configuration of unplugin-vue-router.

1 Answers

In composition-api router is imported from vue-router plugin.

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');
  }
});

Check vue-router for more details.

Related