In this tutorial, we will learn how to install and configure Vue Router in a Vue.js application. Vue Router is the official router for Vue.js and it integrates seamlessly into Vue.js core. It makes building Single Page Applications with Vue.js a lot more enjoyable.
By the end of this tutorial, you will:
Prerequisites: Basic understanding of Vue.js.
Firstly, you need to have a Vue.js project set up. If you don't have one, you can create a new one using Vue CLI. Once you have your project, you can install Vue Router.
npm install vue-router
After the installation, you need to import Vue Router into your main.js file and tell Vue.js to use it.
// main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
Next, define your routes. Each route should map to a component. When a user visits a route, the corresponding component is rendered.
// main.js
const routes = [
{ path: '/', component: HomeComponent },
{ path: '/about', component: AboutComponent }
]
Finally, create the router instance and pass the 'routes' option. You can also pass additional options here, but we will focus on 'routes' for now.
// main.js
const router = new VueRouter({
routes // short for `routes: routes`
})
Then, you tell Vue to use this router instance.
// main.js
const app = new Vue({
router
}).$mount('#app')
Below is a complete example of what your main.js file might look like.
// main.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeComponent from './components/Home.vue'
import AboutComponent from './components/About.vue'
Vue.use(VueRouter)
const routes = [
{ path: '/', component: HomeComponent },
{ path: '/about', component: AboutComponent }
]
const router = new VueRouter({
routes // short for `routes: routes`
})
const app = new Vue({
router
}).$mount('#app')
In this code:
In this tutorial, we have learned how to install and configure Vue Router in a Vue.js application. We have seen how to define routes mapping them to components and how to tell Vue to use these routes.
Next steps for learning could include learning how to use route parameters, nested routes, or programmatic navigation. You can find more information in the Vue Router documentation.
Install Vue Router in a new Vue.js project and define two routes: /
and /about
. Each route should render a different component. Test your application by visiting both routes.
Extend the application from exercise 1 by adding a navigation bar with links to both routes. Use the <router-link>
component for this.
Extend the application from exercise 2 by adding a nested route. The nested route should be /about/team
and it should render a TeamComponent
.
Solutions and explanations for these exercises can also be found in the Vue Router documentation. For further practice, try to add more routes and components to your application. Also, experiment with other features of Vue Router like route parameters or programmatic navigation.