Vue Router example – with Nav Bar, Dynamic Route & Nested Routes

vue-router-example-feature-image

Vue Router deeply integrates with Vue.js that we can use to build single-page Vue Application in simple way. In this tutorial, we’re gonna look at a Vue Router example that allows us to navigate among tabs and dynamically show item details from a item list with Nav bar, Dynamic Route and Nested Routes.

More Practice:
Spring Boot + Vue.js example | Spring Data JPA + REST + PostgreSQL CRUD
Spring Boot + Vue.js example | Spring Data JPA + REST + MySQL CRUD

Vue Router example Overview

Goal

vue-router-example-nav-bar-dynamic-route-nested-routes-result

We can:
– click on Nav Bar button to change view among Pages.
– click on any Customer to show details.

Demo

Vue Router

When adding Vue Router to Vue App, we have 2 core actions:
– map components to the routes
– let Vue Router know where to render them

Add Vue Router to Project

– Run command: npm install vue-router.
– Import router to main.js:

import Vue from "vue";
import App from "./App.vue";
import router from './router'

Vue.config.productionTip = false;

new Vue({
  router, // inject the router to make whole app router-aware
  render: h => h(App)
}).$mount("#app");
Vue Router with Nav Bar

– Define some routes, each route has a path and maps to a component:
src/router.js

import Vue from "vue";
import Router from "vue-router";
import CustomersList from "./components/CustomersList.vue";
import AddCustomer from "./components/AddCustomer.vue";
import SearchCustomers from "./components/SearchCustomers.vue";

Vue.use(Router);

export default new Router({
  // get rid of the hash (#) in Url
  // the hash (#) helps the page not to be reloaded when the URL changes
  mode: "history",
  routes: [
    {
      path: "/",
      name: "customers",
      alias: "/customer", // go '/', the URL remains '/', but it wcill be matched if visiting '/customer'
      component: CustomersList
    },
    {
      path: "/add",
      name: "add",
      component: AddCustomer
    },
    {
      path: "/search",
      name: "search",
      component: SearchCustomers
    }
  ]
});

src/App.vue


– We use router-link component for navigation and specify the link with ‘to’ prop. By default, <router-link> will be rendered as an <a> tag.
router-view is the router outlet that render the matched component.

Vue Router with Dynamic Route

For mapping routes with the given pattern to the same component:
With path: "/customer/:id", urls like /customer/1 and /customer/42 will both map to the same route:
router.js

const router = new VueRouter({
  routes: [
    { 
      path: "/customer/:id",
      name: "customer-details",
      component: Customer
    }
  ]
});

When a route is matched, the value of the dynamic segments will be exposed as this.$route.params in every component. Therefore, we can render the current id with this.$route.params.id:
Customer.vue




Vue Router with Nested Routes

To render components into another one, we need to use the children option in Vue Router constructor config:
router.js

export default new Router({
    routes: [
        {
            path: "/",
            name: "customers",
            component: CustomersList,
            children: [
                {
                    path: "/customer/:id",
                    name: "customer-details",
                    component: Customer
                }
            ]
        }
    ]
});

Then add the child component inside the parent component’s template:
CustomersList.vue


We use Named Route name: 'customer-details' to make link to component, and we can also pass an object ({name, id}) to the router-link component:

Customer ABC
Project Structure

vue-router-example-nav-bar-dynamic-route-nested-routes-project-structure

We have:
– Components: CustomersList, AddCustomer, SearchCustomers are corresponding to 3 Navbar buttons: Customers, Add, Search.
Customer components is the child of CustomersList component, its UI view is embeded into parent component using <router-view> tag.
App.vue contains the whole application template with Nav bar and <router-view>.
– We define routes, each route has a path and maps to a component in router.js.
main.js mount App component with router to be injected.

Practice

Technologies

– Vue CLI 3.0.1
– Vue 2.5.17
– Vue Router 3.0.1

Setup Vue Project
Install vue-cli

For use Vue CLI anywhere, run command:
npm install -g vue-cli

Init Project

Point cmd to the folder you want to save Project folder, run command:
npm create vue-router-example

You will see 2 options, choose default:

vue-create-project-config

Add Vue Router to Project

– Run command: npm install vue-router.
– Import router to main.js:

import Vue from "vue";
import App from "./App.vue";
import router from './router'

Vue.config.productionTip = false;

new Vue({
  router, // inject the router to make whole app router-aware
  render: h => h(App)
}).$mount("#app");
Define Routes

src/router.js:

import Vue from "vue";
import Router from "vue-router";
import CustomersList from "./components/CustomersList.vue";
import AddCustomer from "./components/AddCustomer.vue";
import SearchCustomers from "./components/SearchCustomers.vue";
import Customer from "./components/Customer.vue";

Vue.use(Router);

export default new Router({
  mode: "history",
  routes: [
    {
      path: "/",
      name: "customers",
      alias: "/customer",
      component: CustomersList,
      children: [
        {
          path: "/customer/:id",
          name: "customer-details",
          component: Customer
        }
      ]
    },
    {
      path: "/add",
      name: "add",
      component: AddCustomer
    },
    {
      path: "/search",
      name: "search",
      component: SearchCustomers
    }
  ]
});
App template with Navbar and router-view

src/App.vue:






Mock Components

components/AddCustomer.vue:


components/SearchCustomers.vue:


Components with Dynamic Route & Nested Routes
Parent Component

components/CustomersList.vue:






Child Component

components/CustomersList.vue:




Source Code

vue-router-example

22 thoughts on “Vue Router example – with Nav Bar, Dynamic Route & Nested Routes”

  1. Hi there to every body, it’s myy first goo to see of this webpage;
    this webpage contains amazing and really excellent data in support
    of readers.

  2. I have found very nteresting your article.It’s pretty woprth enough for me.
    In my view, if alll website owners aand bloggers made good content as you did, the web will
    bee a loot more useful than ever before.

  3. I have learn some excellent stuff һere. Definitely worth bookmarking for revisiting.
    I surprise hhow soo muc attempt youu place too make this tyupe of fantastic іnformative website.

  4. You rеally maкe itt appeasr so easy alߋng with your presentation but I in fijding tһiѕ topic to be
    really one thing which I believe I’d by no means understand.

    It ѕort of feeⅼs too complex and very vast for mе. I’m ⅼooing forward tօ your
    next post, Ι will attempt to get thee cling of it!

  5. This design is іncredible! You most certainly know how
    t᧐ keep a reader entertained. Between your wit and your videoѕ, I wwaѕ almost
    m᧐ved to start my own blog (wеll, almost…HaHa!)
    Wonderful јob. I realⅼy loved what ʏyou had to ѕay,
    and more than that, how youu prеsented it. Too cool!

  6. Hello, Neat post. There’s a problem together with your website in internet explorer, may check this?
    IE still is the marketplace leader and a good portion of people will leave out your fantastic
    writing because of this problem.

  7. Tһis esiɡn is steller! Υou definitely know һow to keep a reader entertained.

    Between your wit and your videos, I was almost movеd to start mmy own bⅼog
    (well, almoѕt…HaHa!) Grеat job. I reаⅼly loved what you had to say,and moore than that,
    how you predented it. Ꭲoo cool!

Leave a Reply

Your email address will not be published. Required fields are marked *