'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:
And here is my script:
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.
Solution 1:[1]
import { useRouter } from 'vue-router';
const router = useRouter();
const login = () => {
...your code
router.push({path: 'your-path-here'})
}
Solution 2:[2]
You need to call useRouter
in your script. Something like this:
<script setup>
import { useRouter } from 'vue-router';
const router = useRouter();
router.push(redirectPath);
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | mateocodeo |
Solution 2 | Daniel Storey |