Member-only story
Passing Props to Vue.js Route Components with Vue Router
Vue.js is an easy to use web app framework that we can use to develop interactive front end apps.
Vue Router is a URL router that maps URLs to components.
In this article, we’ll look at how to pass props to route components with the Vue Router.
Passing Props
Using the $route
in our component creates a tight coupling between the $route
object and the component. Therefore, it limits the flexibility of the component as it can be only used on certain URLs.
We can decouple the component from the router by using the props
option.
For example, instead of writing:
const User = { template: "<div>User {{ $route.params.id }}</div>" };
const routes = [
{
path: "/user/:id",
component: User
}
];const router = new VueRouter({
routes
});new Vue({
el: "#app",
router
});
We instead write:
src/index.js
:
const User = { template: "<div>User {{ id }}</div>" };
const routes = [
{
path: "/user/:id",
component: User,
props: true
}
];const router = new VueRouter({
routes
});new Vue({
el: "#app",
router
});
src/index.html
:
<!DOCTYPE html>
<html>
<head>
<title>App</title>
<meta charset="UTF-8" />
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<router-view></router-view>
</div>
<script src="src/index.js"></script>
</body>
</html>
If we have multiple router-views
, then we have to define the props
on each one as follows:
src/index.js
:
const Foo = { props: ["id"], template: "<div>foo {{id}}</div>" };
const Bar = { props: ["id"], template: "<div>bar {{id}}</div>" };
const routes = [
{
path: "/:id",
components: { default: Foo, bar: Bar },
props: { default: true, bar: true }
}
];const router = new VueRouter({
routes
});