18

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.

2
  • 4
    useRouter() router.push() router.vuejs.org/guide/advanced/… Commented Apr 14, 2022 at 1: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. Commented Apr 14, 2022 at 2:00

1 Answer 1

30

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.