0% found this document useful (0 votes)
128 views11 pages

Vue Router Tutorial With Example - How To Use Routing in Vuejs

Vue Router is the official router for Vue.js that integrates with Vue's core to simplify building single-page applications. It features nested routing, route parameters, view transitions, and more. The router syncs the URL with the currently displayed view. Basic routing is set up by defining routes and components, then rendering routes with <router-view>. Route parameters allow dynamic segments, and named routes simplify navigation. The router object provides programmatic navigation methods.

Uploaded by

José Arenilla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
128 views11 pages

Vue Router Tutorial With Example - How To Use Routing in Vuejs

Vue Router is the official router for Vue.js that integrates with Vue's core to simplify building single-page applications. It features nested routing, route parameters, view transitions, and more. The router syncs the URL with the currently displayed view. Basic routing is set up by defining routes and components, then rendering routes with <router-view>. Route parameters allow dynamic segments, and named routes simplify navigation. The router object provides programmatic navigation methods.

Uploaded by

José Arenilla
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

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. 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.

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 Vue.js 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 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


Next step is to create three new components inside the src >> components folder.
1. Home.vue
2. Register.vue
3. 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 src >> routes.js file. 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;

Next step is to create a VueRouter instance and pass the routes object. So, we need
to import 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 component 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 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, vue.js 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 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 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 >> routes.js called /student/:id and also
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.

Now inside the student route component, we can reference the route using the
$route and the 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:

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.$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 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 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 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 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 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
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 the http://localhost:8080/404, 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.

You might also like