How to Use Vue Router
Vue Router is the official routing manager for Vue.js. It is deeply integrated with Vue.js core, simplifying the creation of single-page applications. Here are the basic steps to use Vue Router:
Step 1: Installing Vue Router
If you use npm or yarn, you can install Vue Router using the command line:
bashnpm install vue-router # or yarn add vue-router
Step 2: Creating the Router Instance
Import Vue and Vue Router, then use Vue.use(Router) to enable the routing plugin in Vue.
javascriptimport Vue from 'vue'; import Router from 'vue-router'; Vue.use(Router);
Next, define the route configuration where each route maps to a component.
javascriptconst routes = [ { path: '/', component: Home }, { path: '/about', component: About } ]; const router = new Router({ routes // (shorthand) equivalent to routes: routes });
Step 3: Creating the Vue Instance and Passing router
When initializing the Vue instance, pass the router configuration.
javascriptimport Vue from 'vue'; import App from './App.vue'; import router from './router'; new Vue({ el: '#app', router, render: h => h(App) });
Step 4: Using Routing Within Components
Within Vue components, utilize <router-link> for navigation links and <router-view> as a container for the current route's component.
vue<template> <div> <h1>Home</h1> <router-link to="/about">About Us</router-link> <router-view></router-view> </div> </template>
Example Explanation
Consider a simple Vue application with two pages: Home and About. When the user clicks 'About Us', the page displays the content without reloading.
Route Configuration (router/index.js):
javascriptimport Vue from 'vue'; import Router from 'vue-router'; import Home from '../components/Home.vue'; import About from '../components/About.vue'; Vue.use(Router); export default new Router({ routes: [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', component: About } ] });
Vue Application Entry (main.js):
javascriptimport Vue from 'vue'; import App from './App.vue'; import router from './router'; new Vue({ router, render: h => h(App) }).$mount('#app');
App Component (App.vue):
vue<template> <div id="app"> <router-link to="/">Home</router-link> <router-link to="/about">About</router-link> <router-view/> </div> </template>
By following these steps, we successfully integrate Vue Router into the Vue application, implementing basic routing functionality. This approach for single-page applications provides a smoother user experience, as page transitions do not require reloading, thereby improving application performance.