Navigating Vue Router

Divya Sasidharan Developer Advocate @shortdiv

Why

Routing is essentially the way you navigate through a website or web-application.

Client Side Routing

Client Side Routing vs Server Side Routing

Server Side Routing Client Side Routing ! ! ! Fast time to first paint Fast Routing Optimized for SEO Smooth Transitions " Full page refresh " Slower routing " ! longer time to first paint " Not SEO friendly

SPA = Client Side Routing

What

Vue Router 🚦

. β”œβ”€β”€ src/ β”œβ”€β”€ … β”œβ”€β”€ router.js β”œβ”€β”€ … β”œβ”€β”€ … └── package.json

. β”œβ”€β”€ src/ β”œβ”€β”€ … β”œβ”€β”€ router/ β”œβ”€β”€ index.js β”œβ”€β”€ routes.js β”œβ”€β”€ … β”œβ”€β”€ … └── package.json

How

export default [ { path: "/", name: "dashboard", component: Dashboard }, ] src/router/routes.js

import Vue from "vue"; import Router from "vue-router"; import routes from "./routes"; Vue.use(Router); const router = new Router({ routes, mode: "history" }); export default router; src/router/index.js

import Vue from "vue"; import App from "./App.vue"; import router from "./router"; new Vue({ router, render: h %=> h(App) }).$mount("#app"); src/main.js

When

β€’ Nested route/view mapping β€’ Modular, component-based router configuration β€’ Route params, query, wildcards β€’ View transition effects powered by Vue.js' transition system β€’ Fine-grained navigation control β€’ Links with automatic active CSS classes β€’ HTML5 history mode or hash mode, with auto-fallback in IE9 β€’ Customizable Scroll Behavior

β€’ Nested route/view mapping β€’ Modular, component-based router configuration β€’ Route params, query, wildcards β€’ View transition effects powered by Vue.js' transition system β€’ Fine-grained navigation control β€’ Links with automatic active CSS classes β€’ HTML5 history mode or hash mode, with auto-fallback in IE9 β€’ Customizable Scroll Behavior

Navigation Guards

Demo

Navigation Guards Global Per Route In Component

Global Hooks … const router = new Router({ routes, mode: "history" }); router.beforeEach((to, from, next) %=> { %// … } router.beforeResolve((to, from, next) %=> { %// … } router.afterEach((to, from, next) %=> { %// … } src/router/index.js

Per Guard Hooks export default [ { path: β€œ/", … beforeEnter(to, from, next) { // … }, beforeResolve(to, from, next) { // … } afterEach(to, from, next) { // … } }, src/router/routes.js ]

In Component Hooks export default { name: β€œDashboard”, … beforeRouteEnter(to, from, next) { // … }, beforeRouteUpdate(to, from, next) { // … }, beforeRouteLeave(to, from, next) { // … } } src/router/routes.js

Thanks! @shortdiv https://github.com/shortdiv/gotruejs-in-vue