[Vue Router] Programmatic Navigation

Zhentiw發表於2024-11-26

Navigation is triggered using Vue Router when a <router-link> is clicked, but also can be triggered programmatically from inside our code. In this lesson we’ll look deeper into how this can work. Let me show you where this would be needed, before i show you the new syntax.

✅ Solution: router.push

The solution here is a call to router.push, with the arguments the same as when we use <router-link>. So in our case:

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

defineProps(['event'])
const router = useRouter()

const register = () => {
  // If registered then redirect to event details
  router.push({
    name: 'EventDetails'
  })
}
</script>
<template>
  <p>Regstration form here</p>
  <button @click="register">Register Me!</button>
</template>

Other Push Examples

When you click on a <router-link> it’s simply calling the router.push function inside the code. So as you can imagine, there’s all sorts of combinations you can use just like <router-link>:

// Directly to the path with a single string
router.push('/about')

// Directly to the path with an object
router.push({ path: '/about' })

// Directly to the named path
router.push({ name: 'About' })

// With a dynamic segment as I showed above
router.push({ name: 'EventDetails', params: { id: 3 } })

// With a query ... resulting in /?page=2 in our example app
router.push({ name: 'EventList', query: { page: 2 } })

The params and query values can be variables, as with our example above.

Navigation & Replace

There are times when you might want to navigate the user away from a page, while not pushing a new history entry in their browser (effectively rendering the back button useless for returning to the current page). Perhaps the form you’re submitting, once submitted, should not be allowed to submit again? Beware: This could really confuse your users. 🤣

router.replace({ name: 'EventDetails', params: { id: 3 } })  

This will replace the current page I’m on with the EventDetails page, so the back button will no longer go back to the current page. The arguments are the same as router.push.

Navigating the History Stack

Maybe you’d like to have a custom back & forward button in your interface. This might be useful if you’re building a native mobile app that doesn’t have the same browser bars. In this case you can use go to navigate forward and back in history.

// Go forward a record
router.go(1) 

// Go backward a record
router.go(-1)

相關文章