We are going to learn how to do a simple routing in Vue 3, for this we are going to use the Vue Router plugin which is excellent because it is developed and maintained by the same Vue people, therefore the integration is optimal.
About routing in Vue
Navigation is a fundamental issue for any type of application development that we are carrying out, and Vue or any other client-side JavaScript framework cannot be the exception.
Navigation through routes allows us to link different pages
Pages based on components, therefore we can easily scale the application with new pages and/or components.
You can see the components as if they were a micro app that performs a particular function, a list, a form, a functionality, etc., which, in turn, can be divided into components that are found in other components, but this is another matter..
Create an app in Vue CLI
As always, we are going to start by creating a new application in Vue, for that we are going to use the command line that Vue offers us, known as CLI, we are going to install it globally to our OS:
npm install -g @vue/cliOr
yarn global add @vue/cliRemember that you can use Windows, Linux or Mac since it is multiplatform.
Now, we happily create a new project in Vue 3:
vue create my-vue-routerSelect Vue 3, the preview and with this we will have our basic and clean project in VUE 3 in no time:

Vue Router Basic
Install Vue Router
On the folder of our project that we created previously, we execute:
npm i vue-router@nextCreating the file for the routes
As you can guess, just like the classic operation of any plugin, the linking of the plugin with Vue has to be done in the main instance, here (in the main instance file) you can place any amount of code that in the case of the routes would be the definition of the routes that look like this:
import { createRouter, createWebHistory } from 'vue-router'
import Login from '../components/Login';
import App from '../components/App';
import Group from '../components/Group';
import Chat from '../components/Chat';
const routes = [
{
path: '/',
name: 'App',
component: App
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/group',
name: 'Group',
component: Group
},
{
path: '/chat/:room',
name: 'Chat',
component: Chat
}
]
const router = createRouter({
// 4. createWebHashHistory
history: createWebHistory(),
routes, // short for `routes: routes`
})
export default routerBut obviously defining all the routes that you are going to use; So, to keep this file simple, we're going to make this entire definition in a separate file that we'll then export and define directly within the main Vue instance.
Create and define the router file
Although you can name this file anything and place it in any location, I like to place them inside:
helpers/router.js
Here I am going to assume that we have some dummy components, although they are based on my Electron course in which we were building a Chat application with Firebase and you can get more information from this page in the course section.
Explanation of the above code
There is not much to say here, basically everything is self-explanatory, in the same way:
- The function called createRouter that is part of the Router Vue plugin allows us to define the routes, for this we have to pass a parameter that is the routes, an array with the routes, in which each element has to have the path, which It is the uri and the component, the name is optional and it is useful when we want to create a navigation link (router-link) or programmatically navigate through the router component.
- For the rest, we have to define the URL composition mode for the createRouter function:
- history: createWebHistory(),
Below this array, you'll notice that we created the router itself, using the routes, and also passed createWebHistory. This is used to switch from hashing to history mode within your browser, using the HTML5 History API. The way we set this up is a bit different than what we did in Vue 2 in the same course.
It is simply to indicate if we want a clean URL or a simulated one with a hash mark.
Defining the base template
In our src/App.vue, which is the component that is created by default and loaded by default, we place the skeleton of the app together with the router-view that allows us to create the SPA web; and where the components through which our user navigates and that correspond to the previously defined routes are rendered:
<template>
<div id="nav">
<router-link to="/">App</router-link> |
<router-link to="/login">Login</router-link> |
<router-link to="/group">Group</router-link>
</div>
<router-view />
</template>
<script>
export default {
name: "App",
components: {},
};
</script>You can see each of the components that we use here in a demonstrative way in the github repository that I left you earlier.
Keywords:
- Route: The URL path where this route can be found.
- Name – An optional name to use when binding to this route.
- Component: Which component to load when this route is called.
- Using <router-view> and <router-link>
There are two directives that our Vue app gives us to use in our template:
- <router-view />: when navigating to a route in the browser, this is where the component is rendered, ie where the changing content of our SPA type page is rendered. For example, in our code, going to / will render the Home component where we listed <router-view />.
- <router-link> – This is the directive we use to create links between our different component pages, rather than using <a href>
Why Vue Router?
Vue is powerful for creating Single Page Applications (SPAs): highly interactive web pages that DO NOT refresh when you change from one page to another. If your website has multiple pages (or "views") and you are using Vue, this is why you need Vue Router, as it allows us to create the famous SPA-type pages to do all this without much trouble using one of the most popular and simplest client-side web frameworks on the market.
Redirecting 404 in Vue Router
Here I wanted to solve a small situation that occurs when we enter a route that doesn't exist. I already have the solution, so I will comment on it for a moment.
If we enter the application and try to access any route that doesn't exist, for example, the root directly, we will see a blank page. If we press F12 or check the console, we will see that this route does not match any route because we haven't defined it. That's the reason. The same thing happens if we go to another route that doesn't exist.
Solution 1: 404 using components
There are a couple of ways to solve this. One of them is to create a specific component.
For demonstration purposes, I am using the `ListCategory` component:
// src/router.js
const routes = [
{
path: '/dashboard',
component: Base,
children: [
***
],
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
component: YourComponent404
},
]Solution 2: 404 with Redirection
Suppose the component doesn't exist, or that this component was meant to display a "404" message to indicate to the user that the page does not exist.
In this case, the component might work, but I don't think it's necessary to create a specific one, especially in administrative applications.
It doesn't make much sense to display a 404 page; it's better to redirect the user to a valid page.
To do this, we can place a redirection:
// src/router.js
const routes = [
{
path: '/dashboard',
component: Base,
children: [
***
],
},
{
path: '/:pathMatch(.*)*',
name: 'NotFound',
redirect: '/dashboard/movie'
},
]Explanation of the Redirection
The redirection line works as follows:
- When a route that doesn't exist is entered, for example the root, instead of showing a blank page or a "404" message, the application automatically redirects to a valid route.
- For example, if we enter the root (/) in development (`localhost:5173`) or in production (`vuecodig.com`), and the route doesn't exist, the user will be automatically redirected to the destination page (`/dashboard/movie`).
- This way, we avoid showing the default 404 page and ensure that the application always shows valid content.
Child Routes in Vue Router
The routing system in Vue is a fundamental feature that allows navigation between different pages or components in a Single Page Application (SPA). Vue uses a library called Vue Router to handle routing.
Vue's routing system is based on a configuration file, where the routes to be used and their associated component are stored. Each route can be set with specific parameters and conditions as necessary.
When a user navigates to a specific route in a Vue application, the routing system is responsible for loading the corresponding component and rendering it in the main view. This allows for the creation of a fluid and dynamic user experience, where page changes occur instantaneously, without the need to reload the entire application.
Child Routes or Sub-routes in Vue Router
Now we are going to learn how to create child routes or sub-routes in Vue Router. Through this mechanism, we can group our routes based on the same child component or sub-child of the main route component.
To do this, we use the `children` option, which allows us to define child components within a base component. Additionally, it is necessary to define the base component and the path of the child component.
Remember that for this, you need to understand how to work with routes in Vue and how to correctly structure the parent and child components.
export const routes = [
{
name: 'home',
path: '/test',
component: Home
},
{
path: '/academia',
component: Base,
children: [
{
name: 'index',
path: '',
component: Index
},
{
name: 'my-courses',
path: 'my-courses',
component: MyCourses
},
{
name: 'detail',
path: ':slug/:s?/:c?',
component: Detail
},
{
name: 'register',
path: 'register',
component: Register
},
{
name: 'login',
path: 'login',
component: Login
}
]
}
];
const router = createRouter({
history: createWebHistory(),
routes: routes,
});As you can see, you can define the rest of your routes, whether they have the characteristics of child routes or traditional ones.
In the child component, as you can see, we define its own `router-link` so that the respective content of our child routes can appear:
*Base.vue*
<template>
<div>
<router-link :to="{name:'my-courses'}">Mis cursos</router-link>
<router-view></router-view>
</div>
</template>Optional Parameters in Vue Router
When you are working with Routes in Vue with Vue Router, you will surely be interested in defining parameters for your Vue routes, and more than that, making some of them optional. For this, all you have to do is place the question mark (`?`) in front of the parameter.
Optional parameters are a feature that allows you to define part of a route as optional when navigating between different components.
Optional parameters are defined using the question mark (`?`) in the route. For example, if you have a route `/mypath/post/:id?`, the `id` parameter is considered optional. This means that the routes `/mypath/post` and `/mypath/post/123` will both be valid.
When an optional parameter is used in a route, you can access its value in the corresponding component through `this.$route.params`. If the optional parameter is not present in the URL, its value will be `undefined`.
export const routes = [
...
{
name: 'home',
path: '/test/:param1?',
component: Home
},
...
]Just adding a question mark `?` will make it optional.
Is there another text you'd like me to translate?
Routing the same component, the component doesn't reload in Vue with Vue Router?
Many times when we use Vue Router, we need to call the same component to reload its information; but in Vue, although the URL varies, we will see that the content does not change, this is the behavior that Vue Router has by default but we can force it to update; For that, I bring you a couple of ways:
Not reloading the component, is the expected behavior in Vue, which is trying to be optimal and reuse existing components.
Key in router-view
A somewhat drastic solution is to place a key in our router-view, this will (which is a normal behavior in Vue components) reload this container (the SPA web) as soon as the URL path changes; for that:
<router-view :key="$route.path"></router-view>beforeRouteUpdate in components
Another solution, which is the one I like the most, since it allows us to define this behavior in the components we need, and have more control over what we want to reload and NOT the entire page, is to use the event:
data() {
return {
sectionIndex: this.$route.params.s
classIndex: this.$route.params.c
};
},
beforeRouteUpdate(to) {
this.sectionIndex = to.params.s;
this.classIndex = to.params.c;
},In which, we force the update of our parameters by accessing them, note that with the to parameter, in beforeRouteUpdate, we can obtain exactly the same parameters with which the route of this component works.
In Vue.js, how to use multiple router-views, in one component?
Vue.js is an easy to use web application framework that we can use to develop interactive front-end applications.
In this article, we'll take a look at defining and using named routes and named views with Vue Router; with Vue Router, we can use multiple pages in the same Vue application and change them through the URL to go to other pages; With Vue Router, we can create an application in Vue in the traditional way as we would do in an HTML application that consists of multiple pages, we can have it in Vue.
Named routes
We can add a name to identify a route by adding a name property to our route objects.
Por ejemplo, podemos escribir:
{
name: 'list-category',
path: 'category',
components: {
default: ListCategory,
a: { template: 'Listado de categorías' }
}
},And to reference it, from somewhere, we do the following; this is how we can create a link in Vue Router:
<router-link :to="{ name: 'list-category' }">Listado</router-link>The window that we have with this approach is that when using a routerLink instead of a link in traditional HTML, the page does not reload in its entirety, if not, only the component; In this way, we can have a SPA website very easily with Vue.
Named views
We can have named views with Vue Router.
For example, we can write:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div id="app">
<router-view></router-view>
<router-view name="a"></router-view>
<router-view name="b"></router-view>
</div>
<script>
const Foo = {
template: "<div>foo</div>"
};
const Bar = {
template: "<div>bar</div>"
};
const Baz = {
template: "<div>baz</div>"
};
const routes = [
{
path: "/",
components: {
default: Foo,
a: Bar,
b: Baz
}
}
];
const router = VueRouter.createRouter({
history: VueRouter.createWebHistory(),
routes
});
const app = Vue.createApp({});
app.use(router);
app.mount("#app");
</script>
</body>
</html>We have an object in the routes array called routes, just like we saw in creating routes with Vue Router.
The most important part of the previous code is the component called router-view that we remember is the one that we can use to load the component referenced in the route; In the script above you can see that there are several, but they have names, so now we have router-views with names and defaults that we can use.
In the path path:
path: "/",By having three router-views:
<router-view></router-view>
<router-view name="a"></router-view>
<router-view name="b"></router-view>The one without a name is the one we use by default:
<router-view></router-view>For the other 3, which have a name, they are referenced by the same name:
<router-view name="a"></router-view>
<router-view name="b"></router-view>To reference them from the route definition:
components: {
default: Foo,
a: Bar,
b: Baz
}
I agree to receive announcements of interest about this Blog.
We are going to learn how to do a simple routing in Vue 3, for this we are going to use the Vue Router plugin which is excellent because it is developed and maintained by the same Vue people, therefore the integration is optimal.