Vue Router
Setting up Routing in Vue.js Applications:
Vue Router is the official router for Vue.js, allowing you to build Single Page Applications (SPAs) with client-side routing.
In order to get routing in a Vue, it is required to do the following: first, you need to connect to the Vue and then, start the routing systems.
In the javasrcript application, you first have to install Vue Router using npm or yarn. Subsequently, you bring in Vue and Vue Router, set up your routes, and create a new Vue Router instance, passing the routes configuration. In brief, you link the Vue Router instance to your root Vue instance.
Example:
# Install Vue Router
npm install vue-router
// main.js
import Vue from 'vue';
import VueRouter from 'vue-router';
import App from './App.vue';
import Home from './components/Home.vue';
import About from './components/About.vue';
Vue.use(VueRouter);
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
const router = new VueRouter({
routes
});
new Vue({
router,
render: h => h(App)
}).$mount('#app');
Defining Routes and Route Parameters:
In Vue Router, a route is a set of objects that make up a route. Each route object holds the path which is a URL path, and the component that is to be rendered when the route matches.
Route parameters can be defined by adding a colon (:) the parameter name is placed before the route path.
These variables are thereafter reachable in the component by this.$route.params.
Example:
const routes = [
{ path: '/user/:id', component: User }
];
Navigation Guards:
Navigation guards in Vue Router are hooks provided by the router that allow you to execute code before or after navigation.
There are three types of navigation guards: global guards, per-route guards, and in-component guards.
Global guards are applied to all routes, while per-route guards are applied to specific routes.
In-component guards are defined within individual Vue components and are executed when navigating to or from that component.
Example:
const router = new VueRouter({
routes
});
router.beforeEach((to, from, next) => {
// Perform some checks before navigating
next(); // Call next() to proceed with navigation
});
In this example, beforeEach is a global navigation guard that is executed before each navigation.
It takes three arguments: to, from, and next. The next function must be called to proceed with navigation.
You can use it to redirect, cancel, or modify the navigation flow based on certain conditions.