Skip to main content

Introduction to Vue Router

Vue Router is an essential feature in Vue.js that allows you to build single-page applications (SPAs). It is the official router for Vue.js, and it deeply integrates with Vue.js core to make building Single Page Applications a breeze.

What is Vue Router?

Vue Router is a Vue.js plugin that provides a system for implementing routing in your application. Routing is the ability to move between different parts of an application when a user enters a URL or clicks an element (like a link) within the application.

Installing Vue Router

Before we start using Vue Router, we need to install it. If you are starting a new project, you can set up Vue Router during the initial setup by including it as a plugin. If you already have a Vue project setup, you can add Vue Router by running the following command:

npm install vue-router

After installing, you need to import it in your main.js file and tell Vue to use it:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

Creating Routes

Now that we have Vue Router installed and set up, let's create some routes. Routes are defined in an array of route configuration objects. Each route configuration object contains two properties: path and component.

Here's an example:

import Home from './views/Home.vue'
import About from './views/About.vue'

const routes = [
{ path: '/home', component: Home },
{ path: '/about', component: About }
]

In this example, if a user goes to '/home' they will see the Home component, and if they go to '/about' they will see the About component.

Creating Router Instance

After defining your routes, the next step is to create a router instance and pass the routes option to it:

const router = new VueRouter({
routes // short for `routes: routes`
})

Adding Router to Vue Instance

The final step is to pass the router to the Vue instance:

new Vue({
router,
render: h => h(App)
}).$mount('#app')

To navigate between pages in your Vue application, you can use the <router-link> component that Vue Router provides:

<router-link to="/home">Home</router-link>
<router-link to="/about">About</router-link>

Displaying Current Route

To display the component of the current route, use the <router-view> component:

<router-view></router-view>

And that's it! You now have a basic understanding of how Vue Router works. Vue Router has a lot more features that you can explore such as nested routes, route parameters, navigation guards, and more.

Remember, the best way to learn is by doing. I encourage you to create a new Vue project and try implementing Vue Router yourself. Happy learning!