Vue Router Tutorial With Example | How
To Use Routing in VueJS
Vue Router Tutorial With Example | How To Use Routing in VueJS is today’s topic.
Vue is already an excellent Javascript library that allows you to create dynamic
front-end applications. [Link] is also great for single page applications (SPA). Vue
Router is the official router for [Link]. It profoundly integrates with [Link] core to
make building Single Page Applications with [Link] 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 [Link]’ 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.
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.
If you want to learn more about [Link] then check out this Vue JS 2 – The Complete
Guide (incl. Vue Router & Vuex)
Vue Router Tutorial With Example
installed Vue CLI 3.0, and if you have not installed, then you can install by typing
the following command.
sudo npm install -g @vue/cli
The above command needs to be executed on 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 separately for you. So that we will integrate on our own.
npm install vue-router --save
I have installed the version 3.0.2 because, at this time, this is the latest version. You
might be getting a different version from the future.
Now, you can import the router inside the [Link] application. So let us import inside
the src >> [Link] file.
// [Link]
import Vue from 'vue'
import VueRouter from 'vue-router'
[Link](VueRouter)
Step 2: Basic Routing with [Link]
Inside the src folder, create one file called [Link] and add the following code.
// [Link]
const routes = [];
export default routes;
In the future, we will define the routes inside this file. Now, we need to import
this [Link] file inside the [Link] file.
// [Link]
import Vue from 'vue';
import App from './[Link]';
import VueRouter from 'vue-router';
import routes from './routes';
[Link] = false;
[Link](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
Next step is to create three new components inside the src >> components folder.
1. [Link]
2. [Link]
3. [Link]
// [Link]
<template>
<div>
Home
</div>
</template>
<script>
export default {
}
</script>
// [Link]
<template>
<div>
Register
</div>
</template>
<script>
export default {
}
</script>
// [Link]
<template>
<div>
Login
</div>
</template>
<script>
export default {
}
</script>
Now, import all the components inside src >> [Link] file. We will define the
routes for each component.
// [Link]
import Home from './components/[Link]';
import Register from './components/[Link]';
import Login from './components/[Link]';
const routes = [
{ path: '/', component: Home },
{ path: '/register', component: Register },
{ path: '/login', component: Login },
];
export default routes;
Next step is to create a VueRouter instance and pass the routes object. So, we need
to import [Link] file inside the [Link] file.
// [Link]
import Vue from 'vue';
import App from './[Link]';
import VueRouter from 'vue-router';
import routes from './routes';
[Link] = false;
[Link](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 >>
[Link] file.
// [Link]
<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 component via navigation.
Save this file and go to the terminal and start the vue development server.
npm run serve
Now, go to the [Link] and your URL changes to
this: [Link] it will render the Home component.
We have used the Hash routing which is popular in building a Single Page
Application(SPA).
Vue HTML 5 History Mode Routing
We are using hash mode of routing. We can also use HTML 5 History Mode. By
default, [Link] uses the hash mode. We need to tell vue application externally to do
the history routing.
We need to modify one line of code inside the [Link] file, and we are done.
// [Link]
const router = new VueRouter({mode: 'history', routes});
Now, we can be able to route the components without the hash.
Dynamic routing in [Link]
The above example shows the different view based on the URL, handling the /,
/register and routes.
We can achieve the dynamic segment. The above are were static segments.
Let us define one more route inside the src >> [Link] called /student/:id and also
create a component inside the src >> components folder called [Link].
// [Link]
<template>
<div>
Student
</div>
</template>
<script>
export default {
}
</script>
Now, import the component inside the [Link] file and register that component.
// [Link]
import Home from './components/[Link]';
import Register from './components/[Link]';
import Login from './components/[Link]';
import Student from './components/[Link]';
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.
Now inside the student route component, we can reference the route using the
$route and the access the id using $[Link]. So, write the following code
inside the [Link] file.
// [Link]
<template>
<div>
Student ID is: {{ $[Link] }}
</div>
</template>
<script>
export default {
}
</script>
We are using History mode routing. So go to the: [Link]
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 [Link]() method inside the [Link] file, passing the router
object, in any component of the app you have access to these objects:
1. this.$router: which is the router object.
2. 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.$[Link]()
this.$[Link]()
this.$[Link]()
If you have performed the CRUD operations previously using [Link] as a frontend
then we have used the push() method to change the route programmatically.
Named routes in [Link]
We can simplify the linking process to 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 [Link] file.
// [Link]
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 [Link] file.
// [Link]
<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 perform
the redirecting after some operations are done successfully. 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 [Link] inside the components folder
and add the following code.
// [Link]
<template>
<div></div>
</template>
<script>
export default {
mounted() {
this.$[Link]('/home');
}
}
</script>
So, when the component is mounted, we will redirect the page to the Home
component.
Import this component inside [Link] file and register.
// [Link]
import Home from './components/[Link]';
import Register from './components/[Link]';
import Login from './components/[Link]';
import Student from './components/[Link]';
import Redirect from './components/[Link]';
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: [Link] 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 [Link] and add the following code.
// [Link]
<template>
<div>
Whoops 404!! The page is not available.
<a href="#" @[Link]="back">Go back</a>
</div>
</template>
<script>
export default {
methods: {
back() {
this.$[Link](-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
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 [Link] file.
// [Link]
import Home from './components/[Link]';
import Register from './components/[Link]';
import Login from './components/[Link]';
import Student from './components/[Link]';
import Redirect from './components/[Link]';
import Error from './components/[Link]';
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 the [Link] and you can see the link of the previous
page. Click that link, and you will go to the last page. So it is working and
programmatically.
Finally, Vue Router Tutorial With Example | How To Use Routing in VueJS is over.