This page looks best with JavaScript enabled

Using Props in Vue Router

 ·   ·  ☕ 2 min read

Vue router can pass props to the view on invocation. This can be super useful when same views cater to different contexts, and the context is known at the time of clicking URL. Vue router just catches the context and passes it on to the view.

For example: if you want to show “My Todos” to all users, and “All Todos” to administrators.

Instead of creating two different flavours of the same view, you could incorporate them in one view and pass the context on who clicked the “Todo” link.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// client/router.js

import Vue from "vue";
import Router from "vue-router";
import Home from "./views/Home.vue"; // views!
import store from "./store/index";

Vue.use(Router);

// check if user is logged in
function checkAuth(to, from, next) {
  if (store.state.isLoggedIn) next();
  else "/login";
}

export default new Router({
  mode: "history", // include URL in browser history
  base: "/", // base URL. if your app is at "/app", specify here
  routes: [
    {
      path: "/",
      name: "home",
      component: Home
    },
    {
      path: "/my-todo",
      name: "my-todo",
      component: () => import("./views/Todo.vue") // lazy render
      beforeEnter: checkAuth,
      props: { authMode: "user" }
    },
    {
      path: "/all-todo",
      name: "all-todo",
      component: () => import("./views/Todo.vue") // lazy render
      beforeEnter: checkAuth,
      props: { authMode: "admin" }
    }
  ]
});

The props statement is where the magic happens.

The target component has to receive this prop.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Todo.vue
<template>
  <div>
    Hello, {{ authMode }}
  </div>
</template>

<script>
  export default {
    props: {
      authMode: {
        type: String,
        required: false,
        default: "user",
      },
    },
  };
</script>

We have just defined a normal Vue prop and provided a default value just in case. Depending on the router link (my or admin), router will pass the props to the view, and the view/component can filter to-dos, enforce validation or do other stuff based on user role.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things