We can install the Vue router into an existing Vue.js project by running the following command in the terminal
After a successful installation, we need to import VueRouter in the main.js file in the src directory as well using the following syntax
import router from './router'
After importing the router, you are good to go and use vue-router in your project.
But if you are installing Vue.js using Vue CLI. You won’t need this extra installation step. You can add a vue-router plugin during selecting a preset.
The usage of the vue-router is very simple and easy to use. First, in the template or HTML
<router-link to="/">Home</router-link> |
In this pretty simple and clear example of vue-router. We have created simple navigation using router-link components and provide the link using the prop named ‘to’. The router-link works the same as an anchor ‘a’ tag. It is actually rendered as an ‘a’ tag by default. In the router-view, we will have the relative component which matches the route.
To import a component, we use the following statement
After importing, we have to define the route now and map it to the component. Like this,
We can give multiple routes too, separated by a comma. Like this,
After defining the routes. Pass routes array to the router instances. So, let’s create the router instance as well
routes // short for `routes: routes`
In the end, in the main.js file. We have to create the root instance and mount that as well and inject the routes in it so that the whole app becomes aware of the routes.
By using this injection technique. We can access the router in any component, using
We can now programmatically push routes at the click of a button or anything you want, instead of using the router-link component. For example,
Wrapping up and summary