Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Pass Data Between Routes In A Vue.js Web Application

TwitterFacebookRedditLinkedInHacker News

A few weeks ago I had written about creating routes and navigating a Vue.js web application. It was a basic example of getting around in an application.

Often, when building navigation into your application, you’ll find that you need to pass data from one screen to another. For example, maybe you’re following the master-detail pattern where you have a list of data and you get more information about a particular item in the list by drilling deeper.

We’re going to see how to pass data between routes in a Vue.js web application using a router and URL parameters as well as query parameters.

If you haven’t already read my previous tutorial or are unfamiliar with the vue-router library, I suggest you brush up on it. We’re going to start exploring quickly.

Using URL Parameters to Pass Data Between Routes

Let’s say you have a web application that displays a list of people obtained from some database. This list might only contain first and last name information, but the data in the database might have significantly more information such as address.

In a typical scenario, the primary key or some other identifier is maintained in the list of people and is used for querying the database when requesting the details. Simple values such as identifiers can be easily passed around as URL parameters.

To make this possible, the destination route needs to accept parameters. Extending the previously seen tutorial, we might alter our project’s src/router/index.js file to look like the following:

import Vue from 'vue'
import Router from 'vue-router'
import Page1 from '@/components/page1'
import Page2 from '@/components/page2'

Vue.use(Router)

export default new Router({
    routes: [
        {
            path: "/",
            redirect: {
                name: "Page1"
            }
        },
        {
            path: '/page1',
            name: 'Page1',
            component: Page1
        },
        {
            path: '/page2/:id',
            name: 'Page2',
            component: Page2
        }
    ]
})

Notice the Page2 route now contains an :id in the path. The colon indicates that we’re working with a variable, rather than more of the actual path.

If we open the project’s src/components/page1.vue file, the <template> block might have the following markup:

<template>
    <div class="hello">
        <h1>{{ msg }}</h1>
        <router-link :to="{ name: 'Page2', params: { id: 1234 } }">Navigate to Page2</router-link>
    </div>
</template>

In the above snippet we are choosing to pass parameters to the named route. The id will match the parameter previously defined in the route definition. You could have more than one parameter, but use caution as they can easily get out of hand.

On the receiving end we need to figure out how to obtain and work with the route parameter.

Open the project’s src/components/page2.vue file and include the following:

<template>
    <div class="hello">
        <h1>{{ msg }}, your id is {{ id }}</h1>
        <a style="cursor: pointer; text-decoration: underline" v-on:click="navigate()">Navigate to Page1</a>
    </div>
</template>

<script>
    import router from '../router'

    export default {
        name: 'Page2',
        data () {
            return {
                id: 0,
                msg: 'Hey Nic Raboy'
            }
        },
        created() {
            this.id = this.$route.params.id;
        },
        methods: {
            navigate() {
                router.go(-1);
            }
        }
    }
</script>

<style scoped>
    h1, h2 {
        font-weight: normal;
    }

    ul {
        list-style-type: none;
        padding: 0;
    }

    li {
        display: inline-block;
        margin: 0 10px;
    }

    a {
        color: #42b983;
    }
</style>

We’ve added a few things in the above component versus what we had in the previous example.

First you’ll notice that we’re initializing an id value in the data method. This is to prevent any undefined errors from making an appearance.

When the component is created, the created method is called as per the Vue.js lifecycle hooks. In the created method we get the passed id value from the $route.params and set it to our local variable. This local id variable is rendered in the <template> block.

What if we want to pass more complicated data or even optional data? This is where query parameters come into play.

Using Query Parameters to Pass Data Between Routes

Query parameters in Vue.js work similar to router parameters with the exception that they are not required and the route doesn’t need to be altered before-hand.

Head back into the project’s src/components/page1.vue file and alter the <template> block to look like the following:

<template>
    <div class="hello">
        <h1>{{ msg }}</h1>
        <router-link :to="{ name: 'Page2', params: { id: 1234 }, query: { debug: true }}">Navigate to Page2</router-link>
    </div>
</template>

Notice this time we’re passing URL or router parameters as well as a new set of query parameters. These query parameters can be pretty much any number of key value pairs.

Now let’s take a look at how to work with these query parameters on the receiving end.

Open the project’s src/components/page2.vue file and alter the <script> block to have the following JavaScript code:

<script>
    import router from '../router'

    export default {
        name: 'Page2',
        data () {
            return {
                debug: false,
                id: 0,
                msg: 'Hey Nic Raboy'
            }
        },
        created() {
            this.id = this.$route.params.id;
            if(this.$route.query.debug) {
                this.debug = this.$route.query.debug;
            }
        },
        methods: {
            navigate() {
                router.go(-1);
            }
        }
    }
</script>

Just like with the router parameters, we’ve initialized a placeholder variable in the data method. In the created method we check to see if debug is present in the query parameters and if it is, set it to our local variable.

<template>
    <div class="hello">
        <h1>{{ msg }}, your id is {{ id }}</h1>
        <p>Debug mode is currently set to {{ debug }}</p>
        <a style="cursor: pointer; text-decoration: underline" v-on:click="navigate()">Navigate to Page1</a>
    </div>
</template>

In the above <template> block we’re displaying the debug variable like we would any other variable.

Conclusion

You just saw how to pass data between routes in a Vue.js web application using URL parameters and query parameters. If you didn’t read my previous article on navigation, some of what you saw may not make a lot of sense. I encourage you to take a look at it if you haven’t already.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.