Introduction

Passing props to the VueJS router-view component is the same as passing props to a normal Vue Components. This is important when we want to pass data to our custom components that are being loaded by the router.

For this example I am going to pass the data that’s being provided by Laravel project, the code looks like the following.

<router-view :api-token="'{{ auth()->user()->api_token ?? null }}'"></router-view>

In this code, I am passing the api_token that’s being retrieved from the currently authenticated user and pass it with the api-token name to the router-view component. By doing so we will able to access the api-token property from the components and make of it to access any protected endpoints.

VueJS Receiving Props

The next part is how to get the property that we have just passed, so imagine we have UserCardComponent that will require to access to /users/1 but in order to access to this endpoint we need to pass the API token.

<template>
    <div class="user-card">
        <img class="user-image" :src="user.image">
        <h3 class="user-name">{{ user.name }}
    </div>
</template>

<script>
    import axios from "axios";
    export default {
        name: "UserCard",
        props: {
            apiToken: String
        },
        data() {
            user: {},
        },
        mounted() {
            axios.get(`/api/users/1?api_token=${apiToken}`)
                .then(res => this.user = res.data)
        }
    }
</script>

As you can see from the code above, we can retrieve the apiToken that’s being passed from the router-view. please note that we can’t use :apiToken when passing it to the router-view because the HTML does not support camel cased tags attribute.

For more details and information on Passing Props to Route Components, do refer the documentation directly.

Conclusion

By now you will be able to pass any type of prop to the VueJS router and this is only one of the ways to achieve this. Certainly, there are other alternatives out there but I believe this is the easiest to implement so far. If you found this article to be helpful, do share it with your friends and thanks for reading.