By Hassan Djirdeh This article is cross-posted in CSS-Tricks - https://css-tricks.com/build-a-custom-vue-router/ Plenty of tutorials that do a great job in explaining how Vue’s official routing library, , can be integrated into an existing Vue application. does a fantastic job by providing us with the items needed to map an application’s components to different browser URL routes. exist [vue-router](https://router.vuejs.org/en/) vue-router But, simple applications often don’t need a fully fledged routing library like . In this article, we'll build a simple custom client-side router with Vue. By doing so, we’ll gather an understanding of what needs to be handled to construct client-side routing as well as where potential shortcomings can exist. vue-router Though this article assumes basic knowledge in Vue.js; we’ll be explaining things thoroughly as we start to write code! Routing First and foremost: let’s define for those who may be new to the concept. routing In web development, routing often refers to splitting an application’s UIbased on rules derived from the browser URL. Imagine clicking a link and having the URL go from to . That’s routing. https://website.com https://website.com/article/ Routing is often categorized in two main buckets: the client (i.e. the browser) makes a request to the server on . Server-side routing: every URL change the client makes a request to the server upon initial-page load. Any changes to the application UI based on URL routes are then handled on the client. Client-side routing: only Client-side routing is where the term (or SPA for short) comes in. SPAs are web apps that load and are updated with user interaction without the need to make subsequent requests to the server. With routing in SPAs, that dynamically renders different UI. single-page application only once dynamically JavaScript is the driving force Now that we have a brief understanding of client-side routing and SPAs, let’s get an overview of what we’ll be working on! Case Study: Pokémon The app we aim to construct is a simple Pokémon app that displays details of a particular Pokémon based on the URL route. The application will have three unique URL routes: , , and . Based on the URL route entered, a different Pokémon will be shown: /charizard /blastoise /venusaur In addition, footer links exist at the bottom of the application to direct the user to each respective route upon click: Do We Even Need Routing for This? For simple applications like this, we don’t necessarily a client-side router to make our app functional. This particular app could be composed of a simple parent-child component hierarchy that uses Vue to dictate the information that should be displayed. Here’s a that shows just this: need [props](https://vuejs.org/v2/guide/components.html#Props) Pen Though the app would functionally work, it misses a substantial feature that’s expected from most web applications — . We’d want our Pokémon app to be accessible and to show different details for different pathnames: , , and . This would allow users to refresh different pages and keep their location in the app, bookmark the URLs to come back to later, and potentially share the URL with others. These are some of the main benefits of creating routes within an application. responding to browser navigation events /charizard /blastoise /venusaur Now that we have an idea of what we’ll be working on, let’s start building! Preparing the App The easiest way to follow along step-by-step (if you wish to do so) is to clone the GitHub repo I’ve set up: GITHUB REPO When cloned, install the project dependencies with: npm install Let’s take a brief look within the project directory. $ lsREADME.mdindex.htmlnode_modules/package.jsonpublic/src/static/webpack.config.js There also exists the hidden files, and within the project scaffold. .babelrc .gitignore This project is a simple webpack-configured application scaffolded with , the Vue command line interface. [vue-cli](https://github.com/vuejs-templates/webpack-simple) is where we declare the DOM element— — with which we'll use to mount our Vue application: index.html #app <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <link rel="stylesheet" href=" In the tag of the file, we introduce as our application’s CSS framework and our own file that lives in the folder. <head> index.html Bulma styles.css public/ Since our focus is on the usage of Vue.js, the application already has all the custom CSS laid out. The folder is where we’ll be working directly from: src/ $ ls src/app/main.js represents the starting point of our Vue application. It’s where our Vue instance is instantiated, where we declare the parent component that is to be rendered, and the DOM element with which our app is to be mounted to: src/main.js #app import Vue from 'vue';import App from './app/app'; new Vue({ el: '#app', render: h => h(App)}); We’re specifying the component, , from the file to be the main parent component of our application. App src/app/app.js In the directory, there exists two other files - and : src/app app-custom.js app-vue-router.js $ ls src/app/app-custom.jsapp-vue-router.jsapp.js denotes the completed implementation of the application with a custom Vue router (i.e. what we’ll be building in this article). is a completed routing implementation using the library. app-custom.js app-vue-router.js vue-router For the entire article, we’ll only be introducing code to the file. With that said, let’s take a look at the starting code within : src/app/app.js src/app/app.js const CharizardCard = { name: 'charizard-card', template: ` <div class="card card--charizard has-text-weight-bold has-text-white"> <div class="card-image"> <div class="card-image-container"> <img src="../../static/charizard.png"/> </div> </div> <div class="card-content has-text-centered"> <div class="main"> <div class="title has-text-white">Charizard</div> <div class="hp">hp 78</div> </div> <div class="stats columns is-mobile"> <div class="column">&#x1f525;<br> <span class="tag is-warning">Type</span> </div> <div class="column center-column">199 lbs<br> <span class="tag is-warning">Weight</span> </div> <div class="column">1.7 m <br> <span class="tag is-warning">Height</span> </div> </div> </div> </div> `}; const App = { name: 'App', template: ` <div class="container"> <div class="pokemon"> <pokemon-card></pokemon-card> </div> </div> `, components: { 'pokemon-card': CharizardCard }}; export default App; Currently, two components exist: and . The component is a simple template that displays details of the Charizard Pokémon. The component declares the component in its property and renders it as within its . CharizardCard App CharizardCard App CharizardCard components <pokemon-card></pokemon-card> template We currently only have static content with which we’ll be able to see if we run our application: npm run dev And launch : localhost:8080 To get things started, let’s introduce two new components: and that contains details of the Blastoise and Venusaur Pokémon respectively. We can lay out these components right after : BlastoiseCard VenusaurCard CharizardCard const CharizardCard = { // ... };const BlastoiseCard = { name: 'blastoise-card', template: ` <div class="card card--blastoise has-text-weight-bold has-text-white"> <div class="card-image"> <div class="card-image-container"> <img src="../../static/blastoise.png"/> </div> </div> <div class="card-content has-text-centered"> <div class="main"> <div class="title has-text-white">Blastoise</div> <div class="hp">hp 79</div> </div> <div class="stats columns is-mobile"> <div class="column">&#x1f4a7;<br> <span class="tag is-light">Type</span> </div> <div class="column center-column">223 lbs<br> <span class="tag is-light">Weight</span> </div> <div class="column">1.6 m<br> <span class="tag is-light">Height</span> </div> </div> </div> </div> `};const VenusaurCard = { name: 'venusaur-card', template: ` <div class="card card--venusaur has-text-weight-bold has-text-white"> <div class="card-image"> <div class="card-image-container"> <img src="../../static/venusaur.png"/> </div> </div> <div class="card-content has-text-centered"> <div class="main"> <div class="title has-text-white">Venusaur</div> <div class="hp hp-venusaur">hp 80</div> </div> <div class="stats columns is-mobile"> <div class="column">&#x1f343;<br> <span class="tag is-danger">Type</span> </div> <div class="column center-column">220 lbs<br> <span class="tag is-danger">Weight</span> </div> <div class="column">2.0 m<br> <span class="tag is-danger">Height</span> </div> </div> </div> </div> `};const App = { // ... }export default App; With our application components established, we can now begin to think how we’ll create routing between these components. router-view To establish routing, we’ll start by buiding a new component that holds the responsibility to . We’ll create this component in a constant variable named . render a specified component based on the app’s location View Before we create this component, let’s see how we might use it. In the of the component, we’ll remove the declaration of and instead render the upcoming component. In the property; we’ll register the component constant as to be declared in the template. template App <pokemon-card> router-view components View <router-view> const App = { name: 'App', template: ` <div class="container"> <div class="pokemon"> <router-view></router-view> </div> </div> `, components: { 'router-view': View }}; export default App; The component will match the correct Pokémon component based on the URL route. This matching will be dictated in a array that we’ll create. We’ll create this array right above the component: router-view routes App const CharizardCard = { // ... };const BlastoiseCard = { // ... };const VenusaurCard = { // ... }; const routes = [ {path: '/', component: CharizardCard}, {path: '/charizard', component: CharizardCard}, {path: '/blastoise', component: BlastoiseCard}, {path: '/venusaur', component: VenusaurCard}]; const App = { // ... }; export default App; We’ve set each Pokémon path to their own respective component (e.g. will render the component). We’ve also set the root path to the component. /blastoise BlastoiseCard / CharizardCard Let’s now begin to create our component. router-view The component will essentially be a to dynamically switch between components. One way we can do this in Vue is by using the reserved element to establish . router-view mounting point <component> Dynamic Components Let’s create a starting point for to get an understanding of how this works. As mentioned earlier; we’ll create within a constant variable named . So with that said, let’s set up right after our routes declaration: router-view router-view View View const CharizardCard = { // ... };const BlastoiseCard = { // ... };const VenusaurCard = { // ... };const routes = [ // ...];const View = { name: 'router-view', template: `<component :is="currentView"></component>`, data() { return { currentView: CharizardCard } }}; const App = {// ... };export default App; The reserved element will render whatever component the attribute is bound to. Above, we’ve attached the attribute to a data property that simply maps to the component. As of now, our application resembles the starting point by displaying regardless of what the URL route is. <component> is is currentView CharizardCard CharizardCard Though is appropriately rendered within , it’s not currently dynamic. We need to display the correct component based on the URL pathname . To do this, we’ll use the hook to filter the array and return the component that has a that matches the URL path. This would make look something like this: router-view App router-view upon page load created() routes path View const View = { name: 'router-view', template: `<component :is="currentView"></component>`, data() { return { currentView: {} } }, created() { this.currentView = routes.find( route => route.path === window.location.pathname ).component; }}; In , we’re now instantiating with an empty object. In the hook, we’re using JavaScript’s native method to return the first object from that matches . We can then get the component with (where is the returned object from ). data currentView created() find() routes route.path === window.location.pathname object.component object find() Inside a browser environment, is a special object containing the properties of the browser’s current location. We grab the from this object which is the path of the URL. window.location pathname At this stage; we’ll be able to see the different Pokémon Card components based on the state of our browser URL! The component now renders at the route. **BlastoiseCard** **/blastoise** There’s something else we should consider. If a random URL is entered, our app will currently error and present nothing to the view. pathname To avoid this, let’s introduce a simple check to display a “Not Found” template if the URL doesn’t match any existing in the array. We’ll separate out the method to a component method named to avoid repetition. This updates the object to: pathname path routes find() getRouteObject() View const View = { name: 'router-view', template: `<component :is="currentView"></component>`, data() { return { currentView: {} } }, created() { if (this.getRouteObject() === undefined) { this.currentView = { template: ` <h3 class="subtitle has-text-white"> Not Found :(. Pick a Pokémon from the list below! </h3> ` }; } else { this.currentView = this.getRouteObject().component; } }, methods: { getRouteObject() { return routes.find( route => route.path === window.location.pathname ); } }}; If the method returns , we display a "Not Found" template. If returns an object from , we bind to the component of that object. Now if a random URL is entered, the user will be notified: getRouteObject() undefined getRouteObject() routes currentView The “Not Found” view is rendered if the URL does not match any of the values in the routes array. pathname The “Not Found” template tells the user to pick a Pokémon from a list. This list will be the links we’ll create to allow the user to navigate to different URL routes. Awesome! Our app is now responding to some external state, the location of the browser. determines which component should be displayed based on the app’s location. Now, we need to construct links that will . With the location updated, we want to re-render our Vue app and rely on to appropriately determine which component to render. router-view change the location of the browser without making a web request router-view We’ll label these links as components. router-link router-link In web interfaces, we use HTML tags to create links. What we want here is a special type of tag. When the user clicks on this tag, we’ll want the browser to skip its default routine of making a web request to fetch the next page. Instead, we just want to manually update the browser’s location. <a> <a> Let’s compose a component that produces an tag with a special binding. When the user clicks on the component, we’ll use the browser’s to update the browser’s location. router-link <a> click router-link history API Just like we did with , let’s see how we’ll use this component before we build it. router-view In the template of the component, let’s create three elements within a parent element. Rather than using the attribute in , we’ll specify the desired location of the link using a attribute. We’ll also register the upcoming component (from a constant variable) in the property: App <router-link> <div class="pokemon-links"></div> href <router-link> to router-link Link App components const App = { name: 'App', template: ` <div class="container"> <div class="pokemon"> <router-view></router-view> <div class="pokemon-links has-text-centered"> <router-link to="/charizard"></router-link> <router-link to="/blastoise"></router-link> <router-link to="/venusaur"></router-link> </div> </div> </div> `, components: { 'router-view': View, 'router-link': Link }}; We’ll create the object that represents right above the component. We’ve established the component should always be given a attribute (i.e. prop) that has a value of the target location. We can enforce this prop validation requirement like so: Link router-link App router-link to const CharizardCard = { // ... };const BlastoiseCard = { // ... };const VenusaurCard = { // ... }; const routes = [ // ... ]; const View = { // ... }; const Link = { name: 'router-link', props: { to: { type: String, required: true } }}; const App = { // ... }; export default App; We can create the of to consist of an tag with an handler attribute. Upon trigger, the handler will call a component method, labeled , that navigates the browser to the desired location. This navigation will occur with the use of the method. With that said, the constant object will be updated to: template router-link <a> @click @click navigate() [history.pushState()](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState%28%29_method) Link const Link = { name: 'router-link', props: { to: { type: String, required: true } }, template: `<a @click="navigate" :href="to">{{ to }}</a>`, methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); } }}; Within the tag, we’ve bound the value of the prop to the element text content with . <a> to {{ to }} When is triggered, it first calls on the event object to prevent the browser from making a web request for the new location. The method is then called to direct the user to the desired route location. takes three arguments: navigate() preventDefault() history.pushState() history.pushState() a state object to pass serialized state information a title the target URL In our case, there is no state information that’s needed to be passed, so we’ve left the first argument as . Some browsers (e.g. Firefox) currently ignore the second parameter, , hence we’ve left that as as well. null title null The target location, the prop, is passed in to the third and last parameter. Since the prop contains the target location in a relative state, it will be resolved relative to the current URL. In our case, will resolve to to to /blastoise [http://localhost:8080/blastoise](http://localhost:8080/blastoise.) . If we click any of the links now, we’ll notice our browser updates to the correct location without a full page reload. However, our app will not update and render the correct component. This unexpected behaviour happens because when is updating the location of the browser, . We’ll need to trigger our app (or simply just the component) to re-render whenever the location changes. router-link our Vue app is not alerted of the change router-view Though there’s a few ways to accomplish this behaviour, we’ll do this by using a custom . An is a Vue instance responsible in allowing isolated components to subscribe and publish between each other. [EventBus](https://alligator.io/vuejs/global-event-bus/) EventBus custom events At the beginning of the file, we’ll the library and create an with a new instance: import vue EventBus Vue() import Vue from 'vue'; const EventBus = new Vue(); When a link has been clicked, we need to notify the necessary part of the application (i.e. ) that the user is navigating to a particular route. The first step is to create an event emitter using the 's events interface in the method of . We’ll give this custom event a name of : router-view EventBus navigate() router-link navigate const Link = { // ..., methods: { navigate(evt) { evt.preventDefault(); window.history.pushState(null, null, this.to); EventBus.$emit('navigate'); } }}; We can now set the event listener/trigger in the hook of . By setting the custom event listener outside of the statement, the hook of will be updated to: created() router-view if/else created() View const View = { // ..., created() { if (this.getRouteObject() === undefined) { this.currentView = { template: ` <h3 class="subtitle has-text-white"> Not Found :(. Pick a Pokémon from the list below! </h3> ` }; } else { this.currentView = this.getRouteObject().component; } // Event listener for link navigation EventBus.$on('navigate', () => { this.currentView = this.getRouteObject().component; }); }, .. ///}; When the browser’s location changes by clicking a element, this listening function will be invoked, re-rendering to match against the latest URL! <router-link> router-view Great! Our app now navigates appropriately as we click each of the links. There’s one last thing we need to consider. If we try to use the browser back/forward buttons to navigate through the browser history, our application will not currently re-render correctly. Although unexpected, this occurs because when the user clicks or . no event notifier is emitted browser back browser forward To make this work, we’ll use the event handler. [onpopstate](https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onpopstate) The event is fired each time the active history entry changes. A history change is invoked by clicking the or buttons, or calling or programmatically. onpopstate browser back browser forward history.back() history.forward() Right after our creation, let’s set up the event listener to emit the navigate event when a history change is invoked: EventBus onpopstate window.addEventListener('popstate', () => { EventBus.$emit('navigate'); }); Our application will now respond appropriately even when the browser navigation buttons are used! And there we have it! We’ve just built a custom Vue router using an and dynamic components. Even with the tiny size of our app we can enjoy a noticeable performance improvement. Avoiding a full page load also saves hundreds of milliseconds and prevents our app from "blinking" during the page change. EventBus Conclusion I love Vue. One reason as to why — it’s incredibly to use and manipulate Vue components just like we saw in this article. easy In the introduction, we mentioned how Vue provides the library as the official routing library of the framework. We’ve just created simple versions of the same main items that are used in : vue-router vue-router : the array responsible in mapping components to respective URL pathnames. routes : the component that renders a specified app component based on the app’s location router-view : the component that allows the user to change the location of the browser without making a web request. router-link For simple applications, the routing we’ve built (or a variation thereof built by ) can do the minimal amount of work needed to route our applications. very like this one Chris Fritz The library, on the other hand, is built in a more complicated manner and introduces incredibly useful capabilities, often needed in larger applications like: vue-router Consistency between different browsers Nested Routes Navigation Guards Transition Effects Though the library does come with additional boilerplate, it’s fairly easy to integrate once your application is composed of well isolated and distinct components. If you're interested, you can see the components of being used to enable routing in this application . vue-router vue-router here Hopefully this was as enjoyable to you as it was for me in compiling this post! Thanks for reading! — — — — — — — — — — — — — — —♥ — — — — — — — — — — — — — — — This article is an adapted (and summarized) segment from the , Fullstack Vue is a project driven approach to Vue.js since everything is explained within the context of building a larger application. Fullstack Vue is currently available and you can download the first chapter for from the main website: book Fullstack Vue. learning free https://www.fullstack.io/vue
Share Your Thoughts