DEV Community

loading...

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

loizenai
Software Engineer - Founder at https://loizenai.com
・3 min read

https://grokonez.com/frontend/vue-js/vue-router-example-with-nav-bar-dynamic-route-nested-routes

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

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:

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

<template>
    <div id="app">
        <nav>
            <router-link to="/">Customers</router-link>
            <router-link to="/add">Add</router-link>
            <router-link to="/search">Search</router-link>
        </nav>
        <router-view/>
    </div>
</template>
  • 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.

More: https://grokonez.com/frontend/vue-js/vue-router-example-with-nav-bar-dynamic-route-nested-routes

Discussion (0)