Introduction to Vue Router in Vue.js – Episode 12

Posted by

Vue js – Ep. 12 Vue router basics

Vue js – Ep. 12 Vue router basics

Vue router is a library that provides the ability to create and navigate between different pages in a Vue.js application. In this episode, we will cover the basics of Vue router and how to get started with it in your Vue.js project.

Setting up Vue router

To get started with Vue router, you first need to install it using npm or yarn. Open your terminal and run the following command:


$ npm install vue-router

Once Vue router is installed, you can import it into your Vue.js application and use it to define your routes. Here’s an example of how you can set up your routes in an app:


// main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import App from './App.vue'

Vue.use(VueRouter)

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

const router = new VueRouter({
routes
})

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

Creating route components

After setting up your routes, you need to create the corresponding components for each route. Here’s an example of how you can define the Home and About components:


// Home.vue

Home Page

Welcome to the home page!

export default {
// component logic
}

/* component styles */


// About.vue

About Page

Learn more about us!

export default {
// component logic
}

/* component styles */

Using route links

Once you have your routes and components set up, you can use the <router-link> component to create links to navigate between different pages. Here’s an example of how you can use <router-link>:


Home
About

Conclusion

Vue router is an essential part of building a Vue.js application with multiple pages. In this episode, we covered the basics of setting up Vue router, creating route components, and using route links. With Vue router, you can easily create a navigation system for your Vue.js application.