Slide 1

Slide 1 text

Hassan Djirdeh Understanding Client Side Routing with Vue.js @djirdehh

Slide 2

Slide 2 text

Engineering Present ~ 2 years

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

Vue is the Progressive JavaScript framework that is approachable, versatile, and performant. Progressive approachable versatile performant

Slide 6

Slide 6 text

Progressive Get started with a single script tag

Slide 7

Slide 7 text

approachable HTML CSS JS

Slide 8

Slide 8 text

performant Virtual DOM

Slide 9

Slide 9 text

Vuex Vue Router Vue Test Utils versatile

Slide 10

Slide 10 text

Routing Today’s subject: Routing

Slide 11

Slide 11 text

Routing often refers to splitting an applications UI based on rules derived from the browser URL.

Slide 12

Slide 12 text

https://www.twitter.com/

Slide 13

Slide 13 text

/{userName} https://www.twitter.com/ Dynamic route

Slide 14

Slide 14 text

https://www.twitter.com/{userName} protocol hostname pathname

Slide 15

Slide 15 text

Refresh the page and keep our location in the app Maintain browser back/forward history functionality Bookmark the URL and even share it with others With Routing, we can…

Slide 16

Slide 16 text

Server Side Routing The client (i.e. the browser) makes a request to the server on every URL change. Client Side
 Routing The client only makes a request to the server upon initial-page load. First Meaningful Paint Consistent SEO Performance Faster Routing after Initial Load Smooth transitions and changes Two main methods to achieving routing…

Slide 17

Slide 17 text

Single-page applications
 (SPAs) Client side applications are often labelled as… In modern web apps; JS is the driving force to re-render content in SPAs

Slide 18

Slide 18 text

We’ll be building this Pokemon App that displays details of a Pokemon based on the route.
 
 Live version: http://pokemon-routing.surge.sh/

Slide 19

Slide 19 text

vue-router By the end of the presentation, we’ll build the app with vue-router... but before that, we’ll build our own custom router in Vue.

Slide 20

Slide 20 text

public/ app/ main.js App.vue .babelrc .gitignore .index.html .package.json src/ node_modules/

Slide 21

Slide 21 text

main.js import Vue from 'vue'; import App from './App'; new Vue({ el: '#app', render: h => h(App) });

Slide 22

Slide 22 text

Vue Components Markup (HTML) Logic (JS) Styles (CSS) we’ll take a step back and talk about Vue components

Slide 23

Slide 23 text

Hello Folks!

export default { name: 'NewComponent', data() {}, methods: {} } Vue.component('new-component', { template: ‘

Hello Folks!

’, data() {}, methods: {} }); Vue.component('new-component', { template: ‘

Hello Folks!

’, data() {}, methods: {} });

Hello Folks!

export default { name: 'NewComponent', data() {}, methods: {} } .vue*

Slide 24

Slide 24 text

App.vue
...
Charizard
...
export default { name: "App", };
...
Charizard
...
export default { name: "App", };
...
Charizard
...
export default { name: "App", };

Slide 25

Slide 25 text

http://localhost:8080/ App CharizardCard Let’s externalize the markup to a unique component

Slide 26

Slide 26 text

...
Charizard
...
export default { name: "CharizardCard", }; CharizardCard.vue
...
Charizard
...
export default { name: "CharizardCard", };
...
Charizard
...
export default { name: "CharizardCard", };

Slide 27

Slide 27 text

import CharizardCard from './components/CharizardCard'; export default { name: "App", components: { 'charizard-card': CharizardCard } }; App.vue import CharizardCard from './components/CharizardCard'; export default { name: "App", components: { 'charizard-card': CharizardCard } }; components: { 'charizard-card': CharizardCard } import CharizardCard from './components/CharizardCard';

Slide 28

Slide 28 text

CharizardCard.vue App.vue

Slide 29

Slide 29 text

app/ main.js App.vue components/ BlastoiseCard.vue CharizardCard.vue VenusaurCard.vue We’ll create other files for other components

Slide 30

Slide 30 text

BlastoiseCard.vue CharizardCard.vue VenusaurCard.vue App.vue

Slide 31

Slide 31 text

app/ main.js App.vue components/ router/ RouterLink.vue RouterView.vue routes.js

Slide 32

Slide 32 text

routes.js import BlastoiseCard from '../components/BlastoiseCard'; import CharizardCard from '../components/CharizardCard'; import VenusaurCard from '../components/VenusaurCard'; export default const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard} ]; import BlastoiseCard from '../components/BlastoiseCard'; import CharizardCard from '../components/CharizardCard'; import VenusaurCard from '../components/VenusaurCard'; export default const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard} ]; import BlastoiseCard from '../components/BlastoiseCard'; import CharizardCard from '../components/CharizardCard'; import VenusaurCard from '../components/VenusaurCard'; export default const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard} ]; {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard} export default const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard} ]; pathname!

Slide 33

Slide 33 text

import routes from './routes'; export default { name: "RouterView", data() { return { currentView: {} } } methods: { getRouteObject() { return routes.find( route => route.path === window.location.pathname RouterView.vue <template> <div class="pokemon"> <component :is="currentView"></component> </div> </template> <script> import routes from './routes'; export default { name: "RouterView", data() { return { currentView: {} } } methods: { getRouteObject() { return routes.find( route => route.path === window.location.pathname data() { return { currentView: {} } } <component :is="currentView"></component> We’re using the Dynamic <component /> keyword to create a component that will render another component based on a currentView property

Slide 34

Slide 34 text

import routes from './routes'; export default { name: "RouterView", data() { return { currentView: {} } } methods: { getRouteObject() { return routes.find( route => route.path === window.location.pathname ); } } created() { if (!this.getRouteObject()) { RouterView.vue import routes from './routes'; methods: { getRouteObject() { return routes.find( route => route.path === window.location.pathname ); } } We’ll set up a getRouteObject() method responsible in getting the correct route object from routes based on the window location

Slide 35

Slide 35 text

getRouteObject() { return routes.find( route => route.path === window.location.pathname ); } } created() { if (!this.getRouteObject()) { this.currentView = { template: `

Sorry, we couldn't find that Pokémon :(.

` }; } else { this.currentView = this.getRouteObject().component; } } }; RouterView.vue created() { if (!this.getRouteObject()) { this.currentView = { template: `

Sorry, we couldn't find that Pokémon :(.

` }; } else { this.currentView = this.getRouteObject().component; } } When the component gets created, we’ll use the getRouteObject method to bind the correct component to currentView

Slide 36

Slide 36 text

import CharizardCard from './components/CharizardCard'; export default { name: "App", components: { 'charizard-card': CharizardCard } }; App.vue
import RouterView from './router/RouterView'; export default { name: "App", components: { 'router-view': RouterView } }; Now we’ll have App render the RouterView component

Slide 37

Slide 37 text

/charizard /blastoise /venusaur /pikachu

Slide 38

Slide 38 text

Slide 39

Slide 39 text

RouterLink.vue {{ to }} export default { name: "RouterLink", props: { to: { type: String, required: true } }, methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); } } }; {{ to }} export default { name: "RouterLink", props: { to: { type: String, required: true } }, methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); } } }; {{ to }} export default { name: "RouterLink", props: { to: { type: String, required: true } }, methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); } } }; methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); } } To prevent the browser from making a web request, we’ll create a RouterLink element that pushes a new location with window.history.pushState.

Slide 40

Slide 40 text

Slide 41

Slide 41 text

RouterLink RouterView created() RouterView only picks the correct Pokemon component when it gets created. With RouterLink, we may need to send some event to RouterView when clicked.

Slide 42

Slide 42 text

EventBus

Slide 43

Slide 43 text

An Event Bus is a Vue instance that is used to enable isolated components to subscribe and publish custom events between each other.

Slide 44

Slide 44 text

import Vue from 'vue'; export const EventBus = new Vue(); EventBus = new Vue(); event-bus.js

Slide 45

Slide 45 text

RouterLink.vue {{ to }} import EventBus from './event-bus'; export default { name: "RouterLink", props: { to: { type: String, required: true } }, methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); EventBus.$emit('navigate'); } } }; methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); EventBus.$emit('navigate'); } }

Slide 46

Slide 46 text

RouterView.vue ... import routes from './routes'; import EventBus from './event-bus'; ... created() { // Get correct component upon page load ... // Get correct component upon redirect EventBus.$on('navigate', () => { this.currentView = this.getRouteObject().component; }); }, methods: { getRouteObject() { return routes.find( route => route.path === window.location.pathname ); } } ... ... import routes from './routes'; ... created() { // Get correct component upon page load ... // Get correct component upon redirect EventBus.$on('navigate', () => { this.currentView = this.getRouteObject().component; }); }, methods: { getRouteObject() { return routes.find( route => route.path === window.location.pathname ); } } ... import EventBus from './event-bus';

Slide 47

Slide 47 text

App.vue
import RouterView from './router/RouterView'; import RouterLink from './router/RouterLink'; export default { name: "App", components: { 'router-view': RouterView, ‘router-link': RouterLink } }; import RouterLink from ‘./router/RouterLink';
import RouterView from './router/RouterView'; import RouterLink from './router/RouterLink'; export default { name: "App", components: { 'router-view': RouterView,
 'router-link': RouterLink } };

Slide 48

Slide 48 text

popstate Last item to take care of is browser navigation events. For that we’ll use the popstate event.

Slide 49

Slide 49 text

App.vue ... import RouterView from './router/RouterView'; import RouterLink from './router/RouterLink'; import EventBus from './event-bus'; export default { name: "App", created() { window.addEventListener('popstate', () => { EventBus.$emit('navigate'); }); }, components: { 'router-view': RouterView, 'router-link': RouterLink } }; ... import RouterView from './router/RouterView'; import RouterLink from './router/RouterLink'; import EventBus from './event-bus'; export default { name: "App", created() { window.addEventListener('popstate', () => { EventBus.$emit('navigate'); }); }, components: { 'router-view': RouterView 'router-link': RouterLink } };

Slide 50

Slide 50 text

No content

Slide 51

Slide 51 text

Responsible in mapping components to respective URL pathnames - routes Component responsible in rendering another specified component based on the app’s location - router-view Component that allows the user to change the location of the browser without making a web request - router-link These are also the same three pieces of the vue-router library. So we’ll now switch over to using it.

Slide 52

Slide 52 text

vue-router

Slide 53

Slide 53 text

vue-router is the official router of Vue. It deeply
 integrates with Vue to make building Single Page applications a breeze.

Slide 54

Slide 54 text

npm i vue-router —-save

Slide 55

Slide 55 text

import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter);

Slide 56

Slide 56 text

app/ main.js App.vue components/ router.js

Slide 57

Slide 57 text

import Vue from 'vue'; import VueRouter from 'vue-router'; import ..Card from '.components/..Card'; Vue.use(VueRouter); const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard}, { path: '*', component: { template: `

Sorry. We couldn't find that Pokémon :(.

` } } ]; router.js import Vue from 'vue'; import VueRouter from 'vue-router'; import ..Card from '.components/..Card'; Vue.use(VueRouter); const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard}, { path: '*', component: { template: `

Sorry. We couldn't find that Pokémon :(.

` } } ];

Slide 58

Slide 58 text

const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard}, { path: '*', component: { template: `

Sorry. We couldn't find that Pokémon :(.

` } } ]; export default const router = new VueRouter({ mode: 'history', routes }); router.js export default const router = new VueRouter({ mode: 'history', routes });

Slide 59

Slide 59 text

https://localhost:8080/#/blastoise Never sent to the server Hash mode URLs vue-router’s default mode is hash which allows to have multiple client side routes without having to provide necessary server-side fallbacks.

Slide 60

Slide 60 text

https://localhost:8080/blastoise History mode URLs Since our app is a SPA (Single-page app), we don’t need hash-based URLs. We’ll switch our URLS to mode: history.

Slide 61

Slide 61 text

import Vue from 'vue'; import App from './App'; import router from './router' new Vue({ el: '#app', router, render: h => h(App) }); main.js import Vue from 'vue'; import App from './App'; import router from './router'; new Vue({ el: '#app', router, render: h => h(App) }); To make our app router-aware, we’ll declare the router instance within the entire application Vue instance.

Slide 62

Slide 62 text

App.vue
export default { name: "App" };
export default { name: "App" }; We can use the router-view and router-link elements like we’ve done previously.

Slide 63

Slide 63 text

/charizard /blastoise /venusaur /gyrados

Slide 64

Slide 64 text

- Well Tested - Consistency between different browsers - Dynamic Route Matching - Nested Routes - Navigation Guards vue-router > custom router

Slide 65

Slide 65 text

Dynamic Route Matching app/ components/ BlastoiseCard.vue CharizardCard.vue VenusaurCard.vue AlakazamCard.vue EeveeCard.vue GolbatCard.vue WigglytuffCard.vue MachampCard.vue OnixCard.vue MoltresCard.vue ...Card.vue app/ components/ PokemonCard.vue Having a component file for every Pokemon is unrealistic for a much larger app. With Dynamic Route Matching, we can have multiple routes with the same pattern be matched to a single component.

Slide 66

Slide 66 text

Dynamic Route Matching router.js const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard}, ... ]; Before

Slide 67

Slide 67 text

Dynamic Route Matching router.js const routes = [ {path: '/', component: CharizardCard}, {path: '/pokemon/:id', component: PokemonCard } ]; After

Slide 68

Slide 68 text

... export default { name: "PokemonCard", created() { console.log(this.$route.params.id); } }; Dynamic Route Matching ... export default { name: "PokemonCard", created() { console.log(this.$route.params.id); } }; charizard /pokemon/charizard PokemonCard.vue ... export default { name: "PokemonCard", created() { console.log(this.$route.params.id); } };

Slide 69

Slide 69 text

data: [ { id: 'charizard', hp: 78, type: , weight_lbs: 199, height_m: 1.7, stats: [ ... ], evolutions: [ ... ] }, ... ] Dynamic Route Matching data: [ { id: 'charizard', hp: 78, type: , weight_lbs: 199, height_m: 1.7, stats: [ ... ], evolutions: [ ... ] }, ... ] data: [ { id: 'charizard', hp: 78, type: , weight_lbs: 199, height_m: 1.7, stats: [ ... ], evolutions: [ ... ] }, ... ] With the id route param available in our component - we can use it to retrieve data with a server, make an GET request, etc.

Slide 70

Slide 70 text

{{ pokemonData.id }}
...
export default { name: "PokemonCard", data() { return { pokemonData: {...} } } ... }; PokemonCard.vue
{{ pokemonData.id }}
...
export default { name: "PokemonCard", data() { return { pokemonData: {...} } } ... }; Found with - this.$route.params.id; Bind all data dynamically to component

Slide 71

Slide 71 text

App PokemonCard PokemonStats

Slide 72

Slide 72 text

Nested Routes PokemonCard PokemonStats PokemonCard PokemonEvolutions /pokemon/:id/stats /pokemon/:id/evolutions

Slide 73

Slide 73 text

const routes = [ { path: '/pokemon/:id', component: PokemonCard, children: [ { path: '/stats', component: PokemonStats }, { path: '/evolutions', component: PokemonEvolutions } ] } ] Nested Routes router.js const routes = [ { path: '/pokemon/:id', component: PokemonCard, children: [ { path: '/stats', component: PokemonStats }, { path: '/evolutions', component: PokemonEvolutions } ] } ] const routes = [ { path: '/pokemon/:id', component: PokemonCard, children: [ { path: '/stats', component: PokemonStats }, { path: '/evolutions', component: PokemonEvolutions } ] } ]

Slide 74

Slide 74 text

Nested Routes PokemonCard.vue
...
export default { name: "PokemonCard", };
...
export default { name: "PokemonCard", };
...
export default { name: "CharizardCard", }; RouterView responsible in rendering the correct nested component based on the nested route.

Slide 75

Slide 75 text

Navigation Guards 1. Global - for all navigation routes 2. Per-route - for a certain route 3. In-component - for a certain component

Slide 76

Slide 76 text

const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... }); Global Navigation Guards const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... }); const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... }); const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... }); const router = new VueRouter({ ... }) router.beforeEach((to, from, next) => { // ... }); to.path next(); next('/about'); next(false); next() function must be invoked to complete routing process

Slide 77

Slide 77 text

const router = new VueRouter({ ... }) router.afterEach((to, from) => { // ... }); Global After Hooks router.afterEach((to, from) => { // ... });

Slide 78

Slide 78 text

Per-Route Navigation Guards const routes = [ { path: '/pokemon/:id', component: PokemonCard, beforeEnter: (to, from, next) => { ... } } ]

Slide 79

Slide 79 text

In-Component Navigation Guards ... export default { name: "PokemonCard", beforeRouteEnter (to, from, next) {}, beforeRouteUpdate (to, from, next) {}, beforeRouteLeave (to, from, next) {} }; ... export default { name: "PokemonCard", beforeRouteEnter (to, from, next) {}, beforeRouteUpdate (to, from, next) {}, beforeRouteLeave (to, from, next) {} }; beforeRouteEnter (to, from, next) {}, beforeRouteUpdate (to, from, next) {}, beforeRouteLeave (to, from, next) {},

Slide 80

Slide 80 text

- Programmatic Navigation - Redirects/Aliases - Transitions - Lazy Loading vue-router also provides other additional capabilities…

Slide 81

Slide 81 text

- Vue Router Documentation https://router.vuejs.org/ - Let’s build a Custom Vue Router https://css-tricks.com/build-a-custom-vue-router/

Slide 82

Slide 82 text

No content

Slide 83

Slide 83 text

Details https://www.fullstack.io/vue

Slide 84

Slide 84 text

@djirdehh Hassan Djirdeh