Chapter 5. Client-Side Routing with vue-router
With the core Vue.js library introduced in the previous chapters, we can display and work with data on a page. However, a fully featured website requires more than just that. You may have noticed on some websites that you can navigate around the site without downloading the new page from the server, or if you’ve used another framework before, you’ve probably already met client-side routing.
vue-router is a library for Vue that means we can handle the routing of an app in the browser instead of on the server as in traditional websites. Routing is the act of taking a path (for example, /users/12345/posts) and deciding what should be displayed on the page.
Installation
As with Vue itself, there are multiple ways to install vue-router. You can use a CDN by adding the following:
<scriptsrc="https://unpkg.com/vue-router"></script>
Or if you’re using npm, you can install it using npm install --save vue-router. Then, if you’re using a bundler such as webpack, you will need to call Vue.use(VueRouter) to install vue-router:
importVuefrom'vue';importVueRouterfrom'vue-router';Vue.use(VueRouter);
This step adds components to your app that you will meet in the next few sections.
Basic Usage
To set up the router, you need to give it an array of paths and the corresponding components: when the path is matched, the component will be displayed.
The following creates a simple two-path router:
importPageHomefrom'./components/pages/Home' ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access