Vue Router, the official router for Vue, makes it possible to build Single-Page Applications (SPAs) in Vue. Vue Router lets you map your web app’s components to different browser routes, manage your app’s history stack, and set up advanced routing options.
Getting Started With the Vue Router
To get started with Vue Router, run the following npm (Node Package Manager) command in your preferred directory to create your Vue application:
npm create vue
When prompted whether to add Vue Router for Single Page Application development, select Yes.
Next, open your project in your preferred text editor. Your app’s src directory should include a router folder.
The router folder houses an index.js file containing the JavaScript code for handling routes in your application. The index.js file imports two functions from the vue-router package: createRouter and createWebHistory.
The createRouter function creates a new route configuration from an object. This object contains the history and routes keys and their values. The routes key is an array of objects detailing each route’s configuration, as seen in the above image.
After configuring your routes, you need to export this router instance and import this instance into the main.js file:
import './assets/main.css'import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
const app = createApp(App)
app.use(router)
app.mount('#app')
You imported the router function into the main.js file and then made your Vue app use this router function with the use method.
You can then apply your routes to your Vue app by structuring a similar code block to the one below:
<script setup>
import { RouterLink, RouterView } from 'vue-router'
</script><template>
<header>
<nav>
<RouterLink to="https://www.makeuseof.com/">Home</RouterLink>
<RouterLink to="/about">About</RouterLink>
</nav>
</header>
<RouterView />
</template>
The above code block demonstrates the use of the Vue Router in a Vue component. The code snippet imports two components from the vue-router library: RouterLink and RouterView.
The RouterLink components create links to the Home and About pages in the above code snippet. The to attribute specifies the path to the route you navigate when you click the link. Here, you have one link pointing to the root route (“/”) and another link pointing to the “/about” route.
The component renders the component associated with the current route. It acts as a placeholder where the current route’s content will render. When you navigate to a different route, the component associated with that route will render inside the component.
Adding Params to Your Application’s Routes
Vue Router allows you to pass parameters and queries to routes. Parameters are dynamic parts of the URL, denoted by a colon “:”.
To set your Vue Router to be able to capture parameters in the app’s routes, configure the specific route in your index.js file:
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{
path: "https://www.makeuseof.com/",
name: "home",
component: HomeView,
},
{
path: "/developer/:profileNumber",
name: "developer",
component: () => import("../views/devView.vue"),
},
],
});
The above code block shows a router instance with two routes: home and developer. The developer route shows information about a particular developer based on the developer’s profile number.
Now modify your App.vue file to look like the code snippet below:
<script setup>
import { ref } from "vue";
import { RouterLink, RouterView } from "vue-router";const developer = ref([
{
name: "Chinedu",
profile: 2110,
},
]);
</script>
<template>
<header>
<nav>
<RouterLink to="https://www.makeuseof.com/">Home</RouterLink>
<RouterLink :to="{ path: `/developer/${developer.profile}` }">
Dev Profile
</RouterLink>
</nav>
</header>
<RouterView />
</template>
The above code block sets the developer variable as a reactive object with two properties: name and profile. Then, the second RouterLink component routes to the devView component. You can now access the value of the param you pass into the url in the template block or JavaScript block of the devView component.
To access this value in the template block of the devView component, Vue provides a $route method, an object containing properties that detail the URL’s information. This information includes fullPath, queries, params, and components.
Here is an example of how to access the particular developer’s profile in the devView component with the $route method:
<template>
<div>
<h1>This is developer {{ $route.params.profileNumber }} about page</h1>
</div>
</template>
The above code snippet demonstrates how to use the $route method to access and display the value of the profileNumber parameter within the component’s template.
The params property in the $route method holds the parameters you define in a route. When Vue renders this component, it replaces the value of the $route.params.profileNumber with the actual value you pass in the URL.
For instance, if you visit /developer/123, the displayed message is “This is developer 123 about page”.
You can also access the route information in the JavaScript block of your component. For example:
<script setup>
import { useRoute } from "vue-router";const route = useRoute();
</script>
<template>
<div>
<h1>This is developer {{ route.params.profileNumber }} about page</h1>
</div>
</template>
In the former code block, you accessed the $route object directly within the template to retrieve the route parameters. However, in the updated code block, you imported the function useRoute() from the vue-router package. You assigned the function to a variable which you then used in the template of your Vue component.
With useRoute(), you follow Vue 3’s composition API approach leveraging the reactivity system. This ensures that the component will automatically update when the route parameters change.
Adding Queries to Your Application’s Routes
Queries, or query strings, are optional parameters added to the URL after a question mark “?”. For example, in the route “/search?name=vue”, “name=vue” is a query string where name is the key and vue is the value.
To add a query to a route in Vue Router, you can use the query property of the to object in the RouterLink component. The query property should be an object where each key-value pair represents a query parameter. Here’s an example:
<RouterLink :to="{ name: 'home', query: {name: 'vue'}}">Home</RouterLink>
After adding a query to a route, you can access the query parameters in your Vue components. You can do this with the $route object or the useRoute function, similar to adding route parameters.
Here’s an example of how you use a query parameter in a component:
<template>
{{ $route.query.name }}
</template>
This code snippet demonstrates how to access and render the value of a query parameter (name) from the URL using the $route.query object within the template of a Vue.js component.
Defining a Fallback (404) Page
Vue Router allows you to define a fallback route that will be matched when no other routes match the URL. This is useful for displaying a “404 Not Found” page.
Here’s how you can define a fallback route with the Vue Router:
{
path:'/:pathName(.*)',
name: 'NotFound',
component: () => import('../views/NotFoundView.vue')
}
The /:pathName part indicates a dynamic segment in the URL, and (.*) is a JavaScript regular expression that matches any characters after the dynamic segment. This allows the route to match any path.
When a user navigates to a URL that doesn’t match any other routes, Vue will render the NotFoundView component. You use this approach to handle 404 errors or display a fallback page when a requested route is not found.
Learn to Create Animations in Vue
You learned how to add parameters and queries to your application’s routes. You also learned how to define a fallback page to handle 404 errors. Vue Router provides much more functionality, like setting dynamic and nested routes.
Adding animations and transitions between elements on a web page can significantly enhance the user experience. You need to learn to create transitions and animations in Vue to create a smoother, more engaging, and overall better website.