The vue-router within VueJS allows you to create powerful Single Page Applications with minimal fuss. On a traditional website, each distinct page would constitute a request to the server to load the relevant file. So when someone navigated to http://myapp.com/page-1.html, the
page-1.html file would be served up.
In order to get started with the
vue-router you will first have to include it within your Vue.JS project. This can be done by either adding the
<script> tag with the appropriate link to your application.
Or through the use of
Full installation instructions can be found here: Vue-Router Installation Guide
In order for us to render a series of distinct pages within our Single Page Application we need to add the
<router-view/> tag to our application. This will render the component of our choice depending on the route that is hit.
In order to dictate what component our
<router-view/> component will render, we need to define an array of routes. These represent a
path and a corresponding component like so:
Note, the above code needs both the
SimpleComponent prior to referencing them in our
routes array. We can then define a new
VueRouter which takes in our newly defined
And finally, once we’ve defined our
VueRouter, we add it to our Vue instance like so:
Ta-da! We now have VueJS routing with 2 very simple routes.
Navigating Our Routes
Once we have defined our routes as well as our router, we need a method of traversing between these different routes. In order to do this, we can leverage the
<router-link/> component features a
to prop which we can set to the
path that we wish to navigate to.
Whilst you can use the
<a>tag with the correct
hrefspecified, I would highly recommend using the
<router-link/>component. More information on this can be found here: VueJS Router Link
Say we wished to add a link to our
/simple path that we defined in our above
routes array. We could add the following to just above or
<router-view> component within our
When clicking on this we should see our application’s
<router-view> component change from rendering our
HomePageComponent to our
Full Single-Page Sample
If we were to do this within a single
index.html page then it would look something like so:
And the final project should look something like so:
I threw in a bit of css for this one:
Vue CLI Configuration
When using the
vue cli, we can define that a router is set up for us on creation of our project.
Hopefully, you found this tutorial helpful. We have managed to set up a simple VueJS application that features routing with several routes, each displaying differing components.
If you are interested in some more advanced routing concepts then I would highly recommend checking out the vue-router documentation. It features pages on things like transitions and lazy loading.