Image

touring-vue-router

3 min read
Last update: December 19, 2021

Programmatic Navigation

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.

## 🛑 Problem: Form Submit

The most common place you’ll want to programmatically navigate is when a form is submitted. Likely you’ll only want to change navigation if the creation of the new resource is successful.

So let’s take a look at a simple example, in our Register.vue:

```html
<template>
    <p>Regstration form here</p>
    <button @click="register">Register Me!</button>
</template>
<script>
    export default {
        props: ['event'],
        methods: {
            register() {
                // If registration API call is successful
                // Push back to the event details
            }
        }
    }
</script>
```

For the sake of simplicity we’ll skip the API call itself, assume it was successful, and figure out how to navigate back to the event details page.

## ✅ Solution: this.$router.push

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

    ```html
    <template>
        <p>Regstration form here</p>
        <button @click="register">Register Me!</button>
    </template>
    <script>
        export default {
            props: ['event'],
            methods: {
                register() {
                    // If registration API call is successful
                    this.$router.push({
                        name: 'EventDetails',
                        params: {
                            id: this.event.id
                        }
                    })
                }
            }
        }
    </script>
    ```

    Let’s check this out in action:

    ![https://firebasestorage.googleapis.com/v0/b/vue-mastery.appspot.com/o/flamelink%2Fmedia%2Fbrowser-complete.gif?alt=media&token=8be387cc-0791-4be9-907f-eae212558205](https://firebasestorage.googleapis.com/v0/b/vue-mastery.appspot.com/o/flamelink%2Fmedia%2Fbrowser-complete.gif?alt=media&token=8be387cc-0791-4be9-907f-eae212558205)

    Side note: It’d be nice to give the user some sort of message on this page to let them know their registration is successful. We will cover a creative way to deliver these sort of messages in a future lesson.

    ## 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>`:

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

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

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

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

            // With a query ... resulting in /?page=2 in our example app
            this.$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. 🤣

            ```jsx
            this.$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 `this.$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.

            ```jsx
            // Go forward a record
            this.$router.go(1)

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