Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 993
Josh Davidson Avatar asked Dec 07 '25 05:12

Josh Davidson


1 Answers

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.

like image 190
mateocodeo Avatar answered Dec 09 '25 07:12

mateocodeo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!