Vue3 using script setup, how to access this.$router.push()

17.1k views Asked by At

I am new to Vue3 and am struggling with some examples. I have a simple login component that should redirect to another page but isn't.

Here is my template:

enter image description here

And here is my script:

enter image description here

The problem is that the this.$router is not available, because this is undefined. All the examples that I can find use this coding pattern, but the this variable is undefined in the script setup coding pattern as far as I can tell. What is the alternative?

Thanks.

1

There are 1 answers

1
mateocodeo On

First off import the useRouter composable from vue-router, then use router to access the method.

import { useRouter } from 'vue-router';
const router = useRouter()

function login() { 
  router.push({ path: 'your-path-here' })
}

This is the equivalent of Options API's this.$router.push.