0
0
VueHow-ToBeginner · 3 min read

How to Navigate Programmatically in Vue 3 with Vue Router

In Vue 3, you navigate programmatically by using the useRouter() hook from Vue Router to get the router instance, then call router.push() with the target route. This lets you change pages without user clicks, like after a form submission.
📐

Syntax

To navigate programmatically in Vue 3, first import and call useRouter() inside your setup function to get the router instance. Then use router.push() with a string path or a route object to change the page.

  • useRouter(): Gets the router instance.
  • router.push(location): Navigates to the given location.
  • location: Can be a string path like '/home' or an object like { name: 'home' }.
javascript
import { useRouter } from 'vue-router'

export default {
  setup() {
    const router = useRouter()

    function goToHome() {
      router.push('/home')
    }

    return { goToHome }
  }
}
💻

Example

This example shows a button that, when clicked, navigates programmatically to the '/about' page using router.push().

vue
<template>
  <button @click="goToAbout">Go to About</button>
</template>

<script setup>
import { useRouter } from 'vue-router'

const router = useRouter()

function goToAbout() {
  router.push('/about')
}
</script>
Output
A button labeled 'Go to About' that navigates to the '/about' page when clicked.
⚠️

Common Pitfalls

Common mistakes include trying to use this.$router inside the setup() function, which does not work because this is undefined there. Another mistake is forgetting to import and call useRouter() before using router.push(). Also, passing an invalid route string or object will cause navigation errors.

javascript
/* Wrong way inside setup(): */
export default {
  setup() {
    // this.$router is undefined here
    // this.$router.push('/home') // This will cause an error
  }
}

/* Right way inside setup(): */
import { useRouter } from 'vue-router'

export default {
  setup() {
    const router = useRouter()
    router.push('/home')
  }
}
📊

Quick Reference

MethodDescriptionUsage Example
useRouter()Gets the router instance inside setup()const router = useRouter()
router.push(location)Navigates to a new routerouter.push('/home') or router.push({ name: 'home' })
router.replace(location)Navigates without adding a new history entryrouter.replace('/login')

Key Takeaways

Use the useRouter() hook inside setup() to get the router instance.
Call router.push() with a path or route object to navigate programmatically.
Do not use this.$router inside setup(); it is undefined there.
router.replace() can be used to navigate without adding to browser history.
Always ensure the route path or name you navigate to exists in your router.