Vue-Router: Building “Multi-Page” Single Applications.
Vuejs is a progressive framework that is used to create single-page web applications by using components. Without refreshing the browser, the application can transit from page to page with the help of the Vue router. This help to develop dynamic and excellent front-end applications. Vuejs is famous for building SPA(Single Page Applications) and it has a routing library to manage UI from the frontend itself. This leads to a better user experience and improves application responsiveness. So in this tutorial, let’s discuss how to configure your web application with Vue-router and its use cases.
Why do we need Vue Router?
Every project must implement routing, which is a fundamental requirement. It facilitates the connection between views and URLs. You can implement routing in any contemporary framework. The Vue Routing package from VueJS makes it possible to connect components to routes.
The advantage of using vue-router is that you can change the path of the route without needing to change the path in every <router-link>
or this.$router.push()
call.
So let’s have a look at how to add vue-router to your web application.
Install the latest version of vue-router.
To install the vue-router latest version, use the “@next” after vue-router.
npm install --save vue-router@next
With this installed, we can move on to creating our first routes!
Routing Setup
In order to use the installed router library, we want to import it. After, you need to add configuration to it like which different routes and which different URLs you want to support. To do that, you define a javascript object with the create router and there can have two options.
- routes — Different URLs which you wanna support.
- history — Basically telling the router, how to manage the routing history in the app. When the user clicks somewhere, goes to a different page. Then two pages are added to the browsing history and if the user clicks the back button, history makes sure that the router knows what the last page was. We can use the createWebHistory to use the Vuejs built-in mechanism to remember the user came from.
1. Registering and rendering routes
To register routes, we can add the objects within the routes array.
path :- This is the path of the URL.
component :- Here we define which component should be loaded when the URL visits.
Here is the example code segment of the routes:[] defined.
routes:[ { path: '/about', component: AboutComponent}, { path: '/home', component: HomeComponent}]
In order to be aware of the router, we need to add “app. use(router);” within the main.js file.
To let the view router know, where we render our components, we need to add the <router-view></router-view>. This is able to tell you that, this is the place where the selected router two components should be loaded. You can access the project from here.
2. Navigating with router-link
router-link is almost like an anchor tag. But it is special as it is not loading on a different page. Reloading the entire app and hence losing the current state prevented from using the router-link. View router takes over and analyzes the link the user clicked. This will load the relevant component and updates the URL also.
You can add any HTML element inside the router-link tags. We can add the path URL to this by using the to=``. Below is an example that I used.
<router-link to="/about"> My component </router-link>
The browser will not be refreshed. So this special thing comes up with the vue router and differs from the anchor tag in the HTML. Here is the code snippet.
You can access the project here.
3. Programmatic Navigation
To navigate to a different URL, use router.push. This method pushes a new entry into the history stack. So when the user clicks the browser back button they will be taken to the previous URL. Clicking <router-link :to=``> is the equivalent of calling router.push().
Once you have done some operation in a method, you need to change the route. So here comes this.$router.push method. You can see how I implemented the programmatic navigation in the below code snippet within the confirmInput method.
You can add the backward and forward routes when clicking the browser by using the following commands respectively.
this.$router.back();
this.$router.forward();
You can access the project from here.
4. Passing data with Route Params(Dynamic Segments)
This is another way to pass data between different pages that appear at different routes. Think you need to have the same component with different input in the URL, there the best use case is using the route params for that.
You can define a dynamic path segment by adding a colon and any name of your choice.
{ path: '/teams/:id, component: TeamList}
This route becomes active if you provide a team id along with the URL. So in the relevant component, we can catch the parameter which is passing with the use of parameters defined in it.
const teamId = this.$route.params.id;
In the this.$route.params.id
, id means which we have included into the path parameter. If you have defined the route parameter with another name, you need to mention that id for that. Below is the code snippet, which shows the retrieving of the passing parameter.
You can access the project from here. We can add parameters to the router-link also. This allows for navigating the dynamic paths.
<router-link :to="'/teams/' + id"> View Teams <router-link>
5. Passing params as props
In the above examples, the components are only loadable through routing. Because in the code, we rely on $route. If you want to load the web page, not through the routing, the best method is using the props.
You can add another option in which the props values are also considered within the URL.
{ path: '/teams/:id, component: TeamList, props: true}
This does one important thing, it tells the view router that the dynamic parameters should be passed into this component as props rather than just on the $route property. The value now part of the URL (:id), now will be passed in as a prop into the component.
Now the component is more reusable as we can use it in anywhere, as long as I provide the prop value. This is not strictly tight to routing anymore. You can access the project link from here.
6. Using query params
A query parameter is a thing you might see in some routes and some URLs after the question mark. Like sort equals ascending. A query parameter is basically an optional route parameter that is not needed to find the loaded component but may be used to pass extra information into that component. The below code is used to hold the information about your query parameters.
this.$route.query
Note: The query parameters are not provided as props. The query parameters can be accessed only through the $route.
We have included the ‘getqueryparam’ in the test as in this URL: http://localhost:8080/teams/T1?test=getqueryparam
Then we can see that, only the query param shows in the console as below image. You can access the project from here.
So that’s it for the vue router. There may be more things to discuss within the vue router as this is a broad topic with more things. We learned why we need routing and how to set up the routing, register routes, how work with dynamic paths, and many more.
Hope you all understand the tutorial. If you have any doubt, please feel free to comment here. Thanks and wish you all the very best!