Vue Routing Tutorial: Getting started with Vue Router

Page 1

Vue Routing Tutorial: Getting started with Vue Router www.bacancytechnology.com Please bring clothes, food and medical supplies, and beddings!


VueJS is a robust and most progressive Javascript framework used for developing dynamic and excellent front-end applications. VueJS is also famous for building SPAs (Single Page Applications). Rather than making requests to the backend and rendering the respective pages at the front-end, VueJS provides a Vue Router library to manage the mechanism known as ‘routing.’ This provides a better user experience and improves application responsiveness. In this tutorial, we will learn how to implement Vue Router with our simple Single Page Application. We will develop a small demo application that will have a few pages linked through Vue Router. I’m assuming that you’re already familiar with VueJS. So, let’s begin our journey!


CONTENTS 1. Goal of Vue Routing Tutorial 2. Vue Router Example: Steps to implement Vue Routing 3. Conclusion


Goal of Vue Routing Tutorial


https://youtu.be/4xAIuvAkJWY We will build a demo blog application that will consist of posts (title/description) and comments (related to the post). We will retrieve data using Axios. And for that, we will use these APIs –


To fetch posts – https://jsonplaceholder.typicode.com/posts To fetch post details of post 1 – https://jsonplaceholder.typicode.com/posts /1. To fetch comments of post 1 – https://jsonplaceholder.typicode.com/com ments?postId=1. Each row consists of a blog post. On clicking the blog, we will be able to view comments and post details.


Vue Router Example: Steps to implement Vue Routing


We have divided the steps into four sectionsProject Setup Create components Linking components using Vue Router Dynamic Routing Implementing Page Not Found Follow this step-by-step guide to implement Vue Routing.

1) Project Setup Install vue-cli npm install --global vue-cli


Create a new project vue create vue-router-example When the questions are prompted on your terminal, ensure your answer is “yes” for vue-router installation. Install dependencies cd vue-router-example npm install axios bootstrap-vue Run the server npm run serve

After running the above command, you’ll see the default screen on http://localhost:8080/.


2) Create Components Before moving forward, have a look at the folder structure of vue-router-example


(Folder structure can vary from person to person) Note down the file names and copy-paste the code, respectively. main.js Import IconsPlugin,BCard,BContainer,BCol, and BRow from ‘bootstrap-vue’ import Vue from 'vue' import App from './App.vue' import router from './router' import { IconsPlugin, BCard, BContainer, BCol, BRow, } from "bootstrap-vue";


import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrapvue.css' Vue.use(IconsPlugin) Vue.component("b-card", BCard); Vue.component("b-container", BContainer); Vue.component("b-col", BCol); Vue.component("b-row", BRow); Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')


App.vue The default UI will consist of Home Link and the view based on the routes hit. On clicking Home the UI will be redirected to ‘/’ and display the respective component from file router/index.js. < router-view /> will let us know which route will display which component. <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> </div> <router-view/> </div> </template>


router/index.js Import vue-router package to set the navigating to the components. There are intotal five routes, but primarily we will cover the first two routes for setting up the basic routing. import Vue from 'vue' import VueRouter from 'vue-router' import Posts from "../components/pages/Posts.vue"; Vue.use(VueRouter) const routes = [ { path: '/', redirect: '/posts' }, { path: '/posts', component: Posts, }, ]


const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router /’ defines the default view, here Home page. We will redirect ‘/’ to ‘/posts’ which will display component Posts. Now, let’s see what the Posts component has?


pages/Posts.vue <template> <div> <base-post :posts="allPosts"></base-post> </div> </template> <script> import { Service } from "../../service.js"; import BasePost from '../ui/BasePost.vue'; export default { components: { BasePost }, name: 'Posts', created() { this.getAllPosts(); },


data() { return { allPosts: [], } }, methods: { getAllPosts() { Service.get(`posts`) .then(res => { this.allPosts = res.data; }) .catch(error => console.log(error)); }, } } </script>

We have imported


BasePost from ui/BasePost for displaying the user interface of all the posts Service from service.js to access the remote data using Service.get(‘posts’). On resolving the promise, we will store the response in the array named allPosts, and if the promise is rejected, we will simply console the error. Now let’s see what BasePost.vue component and service.js has? ui/BasePost.vue


<template> <div> <b-card v-for="post in posts" :key="post.id" :style="{ backgroundColor: background(post.id) }" class="post" > <b-row class="row1"> <p class="title"> Title - {{ post.title }} </p> <p class="body" :title="post.body" > Description - {{ post.body.slice(0, 70) + "..." }} </p> </b-row> </b-card>


</div> </template> <script> export default { name: "basePost", props: ["posts"], methods: { background: function(postId) { return postId % 2 == 0 ? "#B5E0D9" : "#FFE6E6"; }, }, }; </script> We have used , < b-row / >, and < b-col / > from the bootstrap-vue. All the posts will be displayed using posts prop with Post Title and Post Description.


Now, let’s see the implementation of API using Axios in the service.js file. service.js We will import ‘axios’ to fetch the data from the base URL – https://jsonplaceholder.typicode.com/ We will create an Axios instance using the ‘create()’ method where the resource is accessed via baseURL prop. import axios from 'axios'; export const Service = axios.create({ baseURL: `https://jsonplaceholder.typicode.com/` }) After implementing the Basic Routing using Vue Router, the UI so far will look like this (excluding style) –


Now, let’s see the dynamic routing. 3) Dynamic Routing When we click on the post, we want to post details to be displayed. And fetch respective data we will use its post.id. We will create one component named PostDetails, and a few make changes in router/index.js and BasePost.vue router/index.js


{ path: '/posts/:id', component: PostDetails }, Now, whenever route ‘/post/:id’ will hit, the PostDetails component will render. As said before, with the click of any post title, we will send its id to the route. To implement this, open the file BasePost.vue and write this code. BasePost.vue <p class="title"> <router-link :to="'/posts/' + post.id" > Title - {{ post.title }} </router-link> </p>


Moving towards the PostDetails component. PostDetails.vue <template> <div> <b-container :style="{ backgroundColor: background(this.postId) }" v-if="postDetails" > <b-row> <b-col cols="12"> <h1>{{ postDetails.title }}</h1> </b-col> </b-row> <div class="postBody"> <b-row align-h="center"> <b-col cols="10"> <p>{{ postDetails.body }}</p> </b-col>


</b-row> </div> <b-row> <b-col cols="12" class="commentTitle"> <h2 style="font-weight: 500">Comments</h2> </b-col> <base-comment :comments="allComments"></basecomment> </b-row> </b-container> <h3 v-else>Loading....</h3> </div> </template> <script> import { Service } from "../../service.js"; import baseComment from "../ui/BaseComment.vue";


export default { name: "PostDetails", components: { baseComment, }, mounted() { this.getPostDetails(); this.getComments(); }, data() { return { postId: this.$route.params.id, postDetails: null, allComments: [], }; }, methods: { getPostDetails() { Service.get(`posts/${this.postId}`) .then((res) => { this.postDetails = { ...res.data,


}; this.getUserDetails(this.postDetails.userI d); }) .catch((error) => console.log(error)); }, getComments() { Service.get(`comments? postId=${this.postId}`).then((res) => { this.allComments = res.data; }); }, background: function(postId) { return postId % 2 == 0 ? "#B5E0D9" : "#FFE6E6"; }, }, }; </script>


Post details will consist of the post title, post description, and post comments. To display that, we will use components from bootstrap-vue. Two API calls are made using the imported Service component – – To fetch post details getPostDetails() { Service.get(`posts/${this.postId}`) .then((res) => { this.postDetails = { ...res.data, }; }) .catch((error) => console.log(error)); },


– To fetch post comments getComments() { Service.get(`comments? postId=${this.postId}`) .then((res) => { this.allComments = res.data; }) .catch((error) => console.log(error)); }, As we will be having a lot of comments related to a single post, we will create a whole new component for displaying comments named BaseComment.vue ui/BaseComment.vue The component will show the comments related to the respective post.


<template> <div> <b-col cols="12" v-if="comments"> <b-col cols="10" v-for="comment in comments" :key="comment.id" class="comment"> {{ comment.body }} </b-col> </b-col> <h5 v-else>Loading....</h5> </div> </template> <script> export default { name: "baseComment", props: ["comments"], }; </script>


After implementing Dynamic Routing, the UI will be something like this (excluding style) –

Heading towards the last section of Vue Router Tutorial – implementation of Page not found. 4) Implementing Page Not Found Create a component named – PageNotFound.vue inside the pages folder and make the required changes in router/index.js.


router/index.js PageNotFound component will render whenever an invalid route hits. { path: '*', component: PageNotFound } PageNotFound.vue <template> <h1>You have entered a wrong url. Try going to <router-link to="/">Home Page</router-link>.</h1> </template> <script> export default { name: 'PageNotFound' } </script> You can find the entire source code here: vue-router-example


Conclusion


So, this was all about implementing a basic and dynamic Vue Routing tutorial with the help of Vue Router. I hope your purpose was served by landing on this blog post. You can learn more about VueJS by reading VueJS tutorials. If you are looking for a helping hand for your ongoing or new Vue.js project, get in touch with us to hire VueJS developer of your choice with the desired skill set. We have 40+ dedicated Vue.js developers available for hire.


Thank You

www.bacancytechnology.com


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.