10

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.

Josh Davidson
  • 147
  • 1
  • 1
  • 5
  • 4
    `useRouter()` router.push() https://router.vuejs.org/guide/advanced/composition-api.html#accessing-the-router-and-current-route-inside-setup – Enfield Li Apr 14 '22 at 01:44
  • 6
    Side note: please avoid posting images of code since none of us can copy, paste and try to run or experiment with an image. Always if possible post code and error messages as code-formatted text. – Hovercraft Full Of Eels Apr 14 '22 at 02:00

1 Answers1

20

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.

kissu
  • 40,416
  • 14
  • 65
  • 133
mateocodeo
  • 251
  • 2
  • 6
  • 2
    Working on a NuxtJs app, facing the same problem and tried this solution but got the following error in console: `[Vue warn]: inject() can only be used inside setup() or functional components.` – fudo Nov 25 '22 at 11:53