Vue is already an excellent Javascript library that allows you to create dynamic front-end applications. Vue.js is also great for single-page applications (SPA). Vue Router is the official router for Vue.js.
It profoundly integrates with Vue.js core to make building Single Page Applications with Vue.js a breeze. Features include:
- Nested route/view mapping.
- It is a modular, component-based router configuration.
- Route params, query, wildcards.
- View transition effects powered by Vue.js’ transition system.
- It has a fine-grained navigation control.
- It links with automatic active CSS classes.
- It has HTML5 history mode or hash mode, with auto-fallback in IE9.
- It has customizable Scroll Behavior.
Vue Router Example
In the JavaScript web application, the router is a part that syncs the currently displayed view with the browser address bar content.
In other words, routing is the part that makes a URL change when you click something on a page and helps to show the correct view or HTML when you navigate the specific URL.
First, we create a Vue project using Vue CLI. I have installed Vue CLI 3.0, and if you have not installed it, you can install it by typing the following command.
sudo npm install -g @vue/cli
The above command needs to be executed in Administrator mode.
Then we can create a new project by typing the following command.
vue create vueroute
Now, go inside the project.
cd vueroute
Step 1: Install Vue Router
Although we can install the vue-router by default while we were creating a new project, let me install it separately for you so that we will integrate it on our own.
npm install vue-router --save
I have installed version 3.0.2 because, at this time, this is the latest version. However, you might be getting a different version in the future.
Now, you can import the router inside the Vue.js application. So let us import inside the src >> main.js file.
// main.js import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter)
Step 2: Basic Routing with Vue.js
Inside the src folder, create one file called routes.js and add the following code.
// routes.js const routes = []; export default routes;
In the future, we will define the routes inside this file. Now, we need to import this routes.js file inside the main.js file.
// main.js import Vue from 'vue'; import App from './App.vue'; import VueRouter from 'vue-router'; import routes from './routes'; Vue.config.productionTip = false; Vue.use(VueRouter); new Vue({ render: h => h(App), routes }).$mount('#app');
So, we have passed the router object while creating a vue instance.
Step 3: Create Vue components
The next step is to create three new components inside the src >> components folder.
- Home.vue
- Register.vue
- Login.vue
// Home.vue <template> <div> Home </div> </template> <script> export default { } </script>
// Register.vue <template> <div> Register </div> </template> <script> export default { } </script>
// Login.vue <template> <div> Login </div> </template> <script> export default { } </script>
Now, import all the components inside the src >> routes.js file. Next, we will define the routes for each component.
// routes.js import Home from './components/Home.vue'; import Register from './components/Register.vue'; import Login from './components/Login.vue'; const routes = [ { path: '/', component: Home }, { path: '/register', component: Register }, { path: '/login', component: Login }, ]; export default routes;
The next step is to create a VueRouter instance and pass the routes object. So, we need to import the routes.js file inside the main.js file.
// main.js import Vue from 'vue'; import App from './App.vue'; import VueRouter from 'vue-router'; import routes from './routes'; Vue.config.productionTip = false; Vue.use(VueRouter); const router = new VueRouter({routes}); new Vue({ router, render: h => h(App) }).$mount('#app');
Also, we need to display the routing components based on the routes. So we can do that by adding the <router-view> component. So let us add that inside src >> App.vue file.
// App.vue <template> <div id="app"> <nav> <router-link to='/'>Home</router-link> <router-link to='/register'>Register</router-link> <router-link to='/login'>Login</router-link> </nav> <router-view /> </div> </template> <script> export default { } </script>
Here, we have created basic navigation in which we have used the <router-link> to change the different components via navigation.
Save this file and go to the terminal and start the vue development server.
npm run serve
Now, go to the http://localhost:8080, and your URL changes to this: http://localhost:8080/#, and it will render the Home component.
We have used Hash routing, which is popular in building a Single Page Application(SPA).
Vue HTML 5 History Mode Routing
We are using the hash mode of routing. We can also use HTML 5 History Mode. By default, vue.js uses the hash mode. Therefore, we need to tell the vue application externally to do the history routing.
We need to modify one line of code inside the main.js file, and we are done.
// main.js const router = new VueRouter({mode: 'history', routes});
Now, we can be able to route the components without the hash.
Dynamic routing in Vue.js
The above example shows the views based on the URL, handling the /, /register, and routes.
We can achieve the dynamic segment. The above are static segments.
Let us define one more route inside the src >> routes.js called /student/:id and create a component inside the src >> components folder called Student.vue.
// Student.vue <template> <div> Student </div> </template> <script> export default { } </script>
Now, import the component inside the routes.js file and register that component.
// main.js import Home from './components/Home.vue'; import Register from './components/Register.vue'; import Login from './components/Login.vue'; import Student from './components/Student.vue'; const routes = [ { path: '/', component: Home }, { path: '/register', component: Register }, { path: '/login', component: Login }, { path: '/student/:id', component: Student }, ]; export default routes;
Here, in the above code, we have pass one parameter called id, and that id is different for every student.
Inside the student route component, we can reference the route using the $route and access the id using $route.params.id. So, write the following code inside the Student.vue file.
// Student.vue <template> <div> Student ID is: {{ $route.params.id }} </div> </template> <script> export default { } </script>
We are using History mode routing. So go to the: http://localhost:8080/student/4, and now we can see that student id on our page.
We can use this id parameter to load the contents from a backend. You can have as many dynamic segments as you want as per your requirement in the same URL.
So, After you call Vue.use() method inside the main.js file, passing the router object, in any component of the app, you have access to these objects:
- this.$router: which is the router object.
- this.$route: which is the current route object.
Vue Router Object
We can access the router object using this.$router from any component when a Vue Router is installed in the root Vue component, and it offers many nice features.
We can make the app navigate to a new route using
this.$router.push()
this.$router.replace()
this.$router.go()
If you have performed the CRUD operations previously using Vue.js as a frontend, then we have used the push() method to change the route programmatically.
Named routes in Vue.js
We can simplify the linking process of navigating to different routes by defining the named routes or designated routes.
Sometimes it is more convenient to identify the route with the name, especially when linking to the route or performing navigations. You can give the route a name in the routes options while creating a Router instance. Now, we will add one property called name to the routes object in a routes.js file.
// routes.js const routes = [ { path: '/', component: Home, name: 'home' }, { path: '/register', component: Register, name: 'register' }, { path: '/login', component: Login, name: 'login' }, { path: '/student/:id', component: Student, name: 'student' }, ];
Now, we can change the links inside the navbar in App.vue file.
// App.vue <template> <div id="app"> <nav> <ul> <li> <router-link :to="{name: 'home'}">Home</router-link> </li> <li> <router-link :to="{name: 'register'}">Register</router-link> </li> <li> <router-link :to="{name: 'login'}">Login</router-link> </li> <li> <router-link :to="{name: 'student', params: {id: 2}}">Student</router-link> </li> </ul> </nav> <router-view /> </div> </template> <script> export default { } </script>
Redirecting Programmatically in Vue Router
In the single-page application, we often face a situation where we need to redirect after some successful operations.
We can redirect the route programmatically using the router object. For example, when the user successfully logged in, we need to redirect to the home route programmatically.
Let us see the following example.
Let us create one more component called Redirect.vue inside the components folder and add the following code.
// Redirect.vue <template> <div></div> </template> <script> export default { mounted() { this.$router.push('/home'); } } </script>
So, when the component is mounted, we will redirect the page to the Home component.
Import this component inside the routes.js file and register.
// main.js import Home from './components/Home.vue'; import Register from './components/Register.vue'; import Login from './components/Login.vue'; import Student from './components/Student.vue'; import Redirect from './components/Redirect.vue'; const routes = [ { path: '/', component: Home, name: 'home' }, { path: '/register', component: Register, name: 'register' }, { path: '/login', component: Login, name: 'login' }, { path: '/student/:id', component: Student, name: 'student' }, { path: '/redirect', component: Redirect, name: 'redirect' }, ]; export default routes;
Now, go to this URL: http://localhost:8080/redirect and see that we are redirecting to the Home component.
Navigating Router History with Go Method
Sometimes, we need to go forward and backward programmatically using navigating history routing. So, let us take an example of a 4o4 page.
Let us create a component inside the components folder called 404.vue and add the following code.
// 404.vue <template> <div> Whoops 404!! The page is not available. <a href="#" @click.prevent="back">Go back</a> </div> </template> <script> export default { methods: { back() { this.$router.go(-1); } } } </script>
So, here, we have defined the 404 page and then put the link that will redirect to the previous route.
Here, Inside the function, I have passed the -1, which means the browser’s one step backward page from the browser, and if we pass 1, then that means one page forward inside the browser.
Now, import inside the routes.js file.
// routes.js import Home from './components/Home.vue'; import Register from './components/Register.vue'; import Login from './components/Login.vue'; import Student from './components/Student.vue'; import Redirect from './components/Redirect.vue'; import Error from './components/404.vue'; const routes = [ { path: '/', component: Home, name: 'home' }, { path: '/register', component: Register, name: 'register' }, { path: '/login', component: Login, name: 'login' }, { path: '/student/:id', component: Student, name: 'student' }, { path: '/redirect', component: Redirect, name: 'redirect' }, { path: '/404', component: Error, name: '404' }, ]; export default routes;
Now, go to http://localhost:8080/404, and you can see the link to the previous page.
Click that link, and you will go to the last page. So it is working and programmatically.
That’s it for the vue router.
Hello. Thank you for this useful tutorial on VueJS with Laravel. I’ve followed your steps but am having issue with this.$router.push(). Home component loads when the page is mounted. But when I click on any of the routes, I end up having two components. One on top of another. I need your help with this. Thank you
I got the same issue, and after checking his example you can see that he has the same problem. So if you fixed it. plz let me know thank a lot.
Hi,
Thanks for this tutorial. It helped me to set up Vue routes from scratch. It works absolutely fine.
Thank you. This was a great intro to Vue routes
This is so useful! I tested everything with Vue js 2 and it also worked!
Thank you So Much .really help me this tutorial
Thanx well explained each and every step.
excellent tutorial.
thanks a lot man
Thanks, tutorial is explained every important think in vue router on short way. You are awesome men 😀
Thanks a lot!
Thank you so much for this.
thats very simple routing 🙂
im ready to next tutor
Thanks! Finally an example that actually works!
awesome!!!
Good Tutorial
I can not express how happy I was to just land in this page and follow the steps of this tutorial and see that everything just…WORKED… you know?
thank so much why is it so difficult to find nice and complete tutorials like this
if this was stack overflow I would create 437 accounts just to upvote your answer
god bless u good night thanks