Single Page Applications are more or less complex apps which load a single HTML page. Every time the user interacts with them, they update their content dynamically using JavaScript.
JavaScript frameworks, like React and Vue, allow us to create SPAs very easily. However, in order to create multi page SPAs using Vue.js, we will need to use a router. The vue-router library is the official router for Vue.js, and it is what we will be using in this article.
In this article, we’ll be discussing how to install a router in Vue.js, and some of the basics on how to create our routes and manage navigation between different views in our application. Let’s get started!
What is vue-router and how does it work?
Vue Router is a JavaScript library that you can use to set up routing in your Vue.js application. With vue-router, you can define routes and map them to components. You can also use the router to manage navigation between different views in your application.
With a very similar functionality to other solutions like React Router DOM, vue-router provides us with many features:
- HTML5 History API support for clean URLs.
- Lazy loading of routes.
- Route params, query, wildcards.
- View transition effects powered by Vue.js’ transition system .
How to install the vue-router library
To install vue-router, you will need to use your preferred Node.js package manager, whether it’s npm or yarn. In your terminal, and inside your project folder, you can run the following command:
npm install vue-router
or
yarn add vue-router
After vue-router has been installed, you will need to import it in your Vue.js application entry point. For example, if you’re using Vue 3 to create your project, you can import vue-router in src/main.js as follows:
import { createApp } from "vue";
import App from "./App.vue";
import router from "./router/index";
createApp(App).use(router).mount("#app");
Installing Vue Router automatically
If you’re using the Vue CLI to create your new project, you will be given the option to add a router from the beginning. This alternative will also give you all the boilerplate and structure you need to start using all the routing functionalities right away.
However, this might not always be an option. If, for example, you’re using Vite to set up your project (a growingly popular alternative), or if you have a previous project that now needs to scale, you’ll have to install the Vue Router library manually, as seen in the previous section.
Create a basic vue-router example
In order to use the functionalities that come with the Vue Router library, you need to create an instance, import it on your main.js file and tell Vue to use it as a router.
For that, you will need to create a new JavaScript file where you’ll add all the basic code the router needs to work properly. For simplicity’s sake, we’ll be creating a folder called router which only has an index.js file inside of it, where we’ll write all of our router’s code.
import { createRouter, createWebHistory } from "vue-router";
const routes = [];
const router = createRouter({
history: createWebHistory(import.meta.env.VITE_APP_ENV),
routes,
});
export default router;
Creating routes in vue-router
After vue-router has been installed and set up in your project, you can start creating routes. A route is defined by a map of HTTP methods and paths, and is associated with a component.
In vue-router, the way to create routes is using the VueRouter constructor function. This function takes an routes object as a parameter, where we can define our routes. The routes need to be defined with an array format:
const routes = [
{
path: "/",
component: HomeComponent
},
{
path: "/about",
component: AboutComponent
},
]
For each route we want to create, we need to add an object inside the routes array. This object needs to have at least two properties: path and component. The path property corresponds to the URL path that we want to map to a component. The component property is the Vue component that will be rendered when the route is accessed.
In the example above, we defined two routes: one for the home page (/) and another for an about page (/about). When the user navigates to the home page, the HomePage component will be rendered. Similarly, when the user navigates to “/about”, the AboutPage component will be the one on display.
Of course, you’ll have to import both components in the Router file in order for this example to work.
You can also use dynamic imports to load components asynchronously. This is particularly useful if you want to lazy-load components, which can improve performance in large applications.
Rendering your view inside a component
Once you have your routes defined, you will need to tell vue-router where to render the view. For that, vue-router provides us with the <router-view> component. This is a placeholder that will be replaced with the component associated with the currently active route.
In order to use this component, you need to add it somewhere in your application, generally in the template of your App.vue file:
<template>
<section>
<router-view />
</section>
</template>
With this code in place, when the user navigates to /about, they will see the AboutPage component rendered inside <router-view>. Similarly, when they navigate back to / (the home page), they’ll see the HomePage component.
Managing navigation between views with vue-router
Once you have your routes defined and your <router-view> component inserted, you can start using vue-router to navigate between different views in your application. The vue-router library provides us with two ways of performing navigation: router-link and the vue-router instance method push.
Router-link is a Vue component that lets us define internal links in our application. It renders an <a> tag by default, but it can also render other types of elements if we pass a tag property to it. For example, we could use a <router-link> to render a <button> element:
<router-link to="/about" tag="button">Go to About</router-link>
This button will take us to the “/about” page when clicked without reloading our app.
On the other hand, the vue-router instance method push can be used to programmatically navigate to a given route. In order to use this method, we need to have a reference to the vue-router instance. The easiest way to do that is by using the “$router” property available on all Vue components if we’re using the Options API:
this.$router.push({ path: '/about' })
Or by creating a local router instance in our component if we’re using the Composition API:
import { useRouter } from 'vue-router';
const router = useRouter();
function redirect() {
router.push({ path: '/about' });
}
With this code in place, when the button is clicked, the user will be redirected to “/about”.
Final thoughts
In this article, we reviewed how to install and set up vue-router in a Vue.js application. We also looked at how to create routes and manage navigation between different views in our application. We hope you found this article helpful, and that it will allow you to create better SPAs with Vue. Thanks for reading!
💬 Leave a comment