SlideShare a Scribd company logo
Vue
Routing
Tutorial:
Getting
started
with Vue
Router
Please bring clothes, food and
medical supplies, and beddings!
www.bacancytechnology.com
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 back-
end 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 –
To fetch post details of post 1 –
To fetch comments of post 1 –
https://jsonplaceholder.typicode.com/posts
https://jsonplaceholder.typicode.com/posts
/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
Project Setup
Create components
Linking components using Vue Router
Dynamic Routing
Implementing Page Not Found
We have divided the steps into four
sections-
Follow this step-by-step guide to
implement Vue Routing.
Install vue-cli
1) Project Setup
npm install --global vue-cli
Create a new project
Install dependencies
vue create vue-router-example
When the questions are prompted on your
terminal, ensure your answer is “yes” for
vue-router installation.
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/bootstrap-
vue.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 in-
total 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.
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.
Now, let’s see the implementation of API
using Axios in the service.js file.
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
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
{
path: '/posts/:id',
component: PostDetails
},
<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"></base-
comment>
</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.
{
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>
router/index.js
PageNotFound component will render
whenever an invalid route hits.
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.
www.bacancytechnology.com
Thank You

More Related Content

What's hot (20)

Why Vue.js?
Why Vue.js?Why Vue.js?
Why Vue.js?
Jonathan Goode
 
Vue 淺談前端建置工具
Vue 淺談前端建置工具Vue 淺談前端建置工具
Vue 淺談前端建置工具
andyyou
 
Love at first Vue
Love at first VueLove at first Vue
Love at first Vue
Dalibor Gogic
 
Vue.js
Vue.jsVue.js
Vue.js
Jadson Santos
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
Hina Chen
 
Vue js and Vue Material
Vue js and Vue MaterialVue js and Vue Material
Vue js and Vue Material
Eueung Mulyana
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8
Brian Ward
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
Bernd Alter
 
Vue JS Intro
Vue JS IntroVue JS Intro
Vue JS Intro
Muhammad Rizki Rijal
 
Vue.js
Vue.jsVue.js
Vue.js
BADR
 
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.js
Zachary Klein
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
Holly Schinsky
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor Barbu
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
TechExeter
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
David Ličen
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
Murat Doğan
 
Vue presentation
Vue presentationVue presentation
Vue presentation
Norbert Nader
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]
Kuro Hsu
 
Scalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JSScalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JS
Galih Pratama
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
Sunghyouk Bae
 
Vue 淺談前端建置工具
Vue 淺談前端建置工具Vue 淺談前端建置工具
Vue 淺談前端建置工具
andyyou
 
Vue js 大型專案架構
Vue js 大型專案架構Vue js 大型專案架構
Vue js 大型專案架構
Hina Chen
 
Vue js and Vue Material
Vue js and Vue MaterialVue js and Vue Material
Vue js and Vue Material
Eueung Mulyana
 
Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8Using VueJS in front of Drupal 8
Using VueJS in front of Drupal 8
Brian Ward
 
Introduction to VueJS & Vuex
Introduction to VueJS & VuexIntroduction to VueJS & Vuex
Introduction to VueJS & Vuex
Bernd Alter
 
Vue.js
Vue.jsVue.js
Vue.js
BADR
 
Room with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.jsRoom with a Vue - Introduction to Vue.js
Room with a Vue - Introduction to Vue.js
Zachary Klein
 
The Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.jsThe Point of Vue - Intro to Vue.js
The Point of Vue - Intro to Vue.js
Holly Schinsky
 
Modern frontend development with VueJs
Modern frontend development with VueJsModern frontend development with VueJs
Modern frontend development with VueJs
Tudor Barbu
 
Enjoy the vue.js
Enjoy the vue.jsEnjoy the vue.js
Enjoy the vue.js
TechExeter
 
VueJS Introduction
VueJS IntroductionVueJS Introduction
VueJS Introduction
David Ličen
 
Vue.js Getting Started
Vue.js Getting StartedVue.js Getting Started
Vue.js Getting Started
Murat Doğan
 
第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]第一次用 Vue.js 就愛上 [改]
第一次用 Vue.js 就愛上 [改]
Kuro Hsu
 
Scalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JSScalable Front-end Development with Vue.JS
Scalable Front-end Development with Vue.JS
Galih Pratama
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
Sunghyouk Bae
 

Similar to Vue routing tutorial getting started with vue router (20)

Vuejs for Angular developers
Vuejs for Angular developersVuejs for Angular developers
Vuejs for Angular developers
Mikhail Kuznetcov
 
Building a Single Page Application with VueJS
Building a Single Page Application with VueJSBuilding a Single Page Application with VueJS
Building a Single Page Application with VueJS
danpastori
 
A New Vue for Web Development
A New Vue for Web DevelopmentA New Vue for Web Development
A New Vue for Web Development
Chad Campbell
 
Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019
Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019
Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019
Codemotion
 
Vue js and Dyploma
Vue js and DyplomaVue js and Dyploma
Vue js and Dyploma
Yoram Kornatzky
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
VueJs Workshop
VueJs WorkshopVueJs Workshop
VueJs Workshop
Unfold UI
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and Vuex
Christoffer Noring
 
Single Page Web Applications with WordPress REST API
Single Page Web Applications with WordPress REST APISingle Page Web Applications with WordPress REST API
Single Page Web Applications with WordPress REST API
Tejaswini Deshpande
 
Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Don't Over-React - just use Vue!
Don't Over-React - just use Vue!
Raymond Camden
 
Intro to VueJS Workshop
Intro to VueJS WorkshopIntro to VueJS Workshop
Intro to VueJS Workshop
Rafael Casuso Romate
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
Commit University
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
Violetta Villani
 
Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.js
Meir Rotstein
 
VueJS: The Simple Revolution
VueJS: The Simple RevolutionVueJS: The Simple Revolution
VueJS: The Simple Revolution
Rafael Casuso Romate
 
Progressive Javascript: Why React when you can Vue?
Progressive Javascript: Why React when you can Vue?Progressive Javascript: Why React when you can Vue?
Progressive Javascript: Why React when you can Vue?
Sonal Raj
 
Vue js 2.x
Vue js 2.xVue js 2.x
Vue js 2.x
Suresh Velusamy
 
Server Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.jsServer Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.js
Jessie Barnett
 
VueJS Best Practices
VueJS Best PracticesVueJS Best Practices
VueJS Best Practices
Fatih Acet
 
Nuxtjs cheat-sheet
Nuxtjs cheat-sheetNuxtjs cheat-sheet
Nuxtjs cheat-sheet
ValeriaCastillo71
 
Vuejs for Angular developers
Vuejs for Angular developersVuejs for Angular developers
Vuejs for Angular developers
Mikhail Kuznetcov
 
Building a Single Page Application with VueJS
Building a Single Page Application with VueJSBuilding a Single Page Application with VueJS
Building a Single Page Application with VueJS
danpastori
 
A New Vue for Web Development
A New Vue for Web DevelopmentA New Vue for Web Development
A New Vue for Web Development
Chad Campbell
 
Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019
Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019
Bermon Painter - Rapid Prototyping with Vue.js - Codemotion Rome 2019
Codemotion
 
How to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScriptHow to Build ToDo App with Vue 3 + TypeScript
How to Build ToDo App with Vue 3 + TypeScript
Katy Slemon
 
VueJs Workshop
VueJs WorkshopVueJs Workshop
VueJs Workshop
Unfold UI
 
Vue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and VuexVue fundamentasl with Testing and Vuex
Vue fundamentasl with Testing and Vuex
Christoffer Noring
 
Single Page Web Applications with WordPress REST API
Single Page Web Applications with WordPress REST APISingle Page Web Applications with WordPress REST API
Single Page Web Applications with WordPress REST API
Tejaswini Deshpande
 
Don't Over-React - just use Vue!
Don't Over-React - just use Vue!Don't Over-React - just use Vue!
Don't Over-React - just use Vue!
Raymond Camden
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
Commit University
 
Level up apps and websites with vue.js
Level up  apps and websites with vue.jsLevel up  apps and websites with vue.js
Level up apps and websites with vue.js
Violetta Villani
 
Introduction to Vue.js
Introduction to Vue.jsIntroduction to Vue.js
Introduction to Vue.js
Meir Rotstein
 
Progressive Javascript: Why React when you can Vue?
Progressive Javascript: Why React when you can Vue?Progressive Javascript: Why React when you can Vue?
Progressive Javascript: Why React when you can Vue?
Sonal Raj
 
Server Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.jsServer Side Rendering with Nuxt.js
Server Side Rendering with Nuxt.js
Jessie Barnett
 
VueJS Best Practices
VueJS Best PracticesVueJS Best Practices
VueJS Best Practices
Fatih Acet
 
Ad

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
Katy Slemon
 
Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
Katy Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
Katy Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
Katy Slemon
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdf
Katy Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
Katy Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
Katy Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
Katy Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Katy Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
Katy Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
Katy Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
Katy Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
Katy Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
Katy Slemon
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
Katy Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Katy Slemon
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdf
Katy Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
Katy Slemon
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
Katy Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
Katy Slemon
 
Ad

Recently uploaded (20)

National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptxFIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Introduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUEIntroduction to Typescript - GDG On Campus EUE
Introduction to Typescript - GDG On Campus EUE
Google Developer Group On Campus European Universities in Egypt
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
National Fuels Treatments Initiative: Building a Seamless Map of Hazardous Fu...
Safe Software
 
Kubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too LateKubernetes Security Act Now Before It’s Too Late
Kubernetes Security Act Now Before It’s Too Late
Michael Furman
 
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven InfrastructureNo-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
No-Code Workflows for CAD & 3D Data: Scaling AI-Driven Infrastructure
Safe Software
 
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptxFIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Seminar: Perspectives on Passkeys & Consumer Adoption.pptx
FIDO Alliance
 
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Scaling GenAI Inference From Prototype to Production: Real-World Lessons in S...
Anish Kumar
 
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdfvertical-cnc-processing-centers-drillteq-v-200-en.pdf
vertical-cnc-processing-centers-drillteq-v-200-en.pdf
AmirStern2
 
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
AudGram Review: Build Visually Appealing, AI-Enhanced Audiograms to Engage Yo...
SOFTTECHHUB
 
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...Your startup on AWS - How to architect and maintain a Lean and Mean account J...
Your startup on AWS - How to architect and maintain a Lean and Mean account J...
angelo60207
 
High Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdfHigh Availability On-Premises FME Flow.pdf
High Availability On-Premises FME Flow.pdf
Safe Software
 
Oracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI ProfessionalOracle Cloud Infrastructure Generative AI Professional
Oracle Cloud Infrastructure Generative AI Professional
VICTOR MAESTRE RAMIREZ
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptxFIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
PyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent IntegrationPyData - Graph Theory for Multi-Agent Integration
PyData - Graph Theory for Multi-Agent Integration
barqawicloud
 
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data ResilienceFloods in Valencia: Two FME-Powered Stories of Data Resilience
Floods in Valencia: Two FME-Powered Stories of Data Resilience
Safe Software
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptxFIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
Murdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementaryMurdledescargadarkweb.pdfvolumen1 100 elementary
Murdledescargadarkweb.pdfvolumen1 100 elementary
JorgeSemperteguiMont
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API CatalogMuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
Providing an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME FlowProviding an OGC API Processes REST Interface for FME Flow
Providing an OGC API Processes REST Interface for FME Flow
Safe Software
 
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdfcnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
cnc-drilling-dowel-inserting-machine-drillteq-d-510-english.pdf
AmirStern2
 
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdfENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
ENERGY CONSUMPTION CALCULATION IN ENERGY-EFFICIENT AIR CONDITIONER.pdf
Muhammad Rizwan Akram
 

Vue routing tutorial getting started with vue router

  • 1. Vue Routing Tutorial: Getting started with Vue Router Please bring clothes, food and medical supplies, and beddings! www.bacancytechnology.com
  • 2. 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 back- end 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!
  • 3. CONTENTS 1. Goal of Vue Routing Tutorial 2. Vue Router Example: Steps to implement Vue Routing 3. Conclusion
  • 5. 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 –
  • 6. To fetch posts – To fetch post details of post 1 – To fetch comments of post 1 – https://jsonplaceholder.typicode.com/posts https://jsonplaceholder.typicode.com/posts /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.
  • 8. Project Setup Create components Linking components using Vue Router Dynamic Routing Implementing Page Not Found We have divided the steps into four sections- Follow this step-by-step guide to implement Vue Routing. Install vue-cli 1) Project Setup npm install --global vue-cli
  • 9. Create a new project Install dependencies vue create vue-router-example When the questions are prompted on your terminal, ensure your answer is “yes” for vue-router installation. 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/.
  • 10. 2) Create Components Before moving forward, have a look at the folder structure of vue-router-example
  • 11. (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";
  • 12. import 'bootstrap/dist/css/bootstrap.css' import 'bootstrap-vue/dist/bootstrap- vue.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')
  • 13. 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>
  • 14. router/index.js Import vue-router package to set the navigating to the components. There are in- total 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, }, ]
  • 15. 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?
  • 16. 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(); },
  • 17. data() { return { allPosts: [], } }, methods: { getAllPosts() { Service.get(`posts`) .then(res => { this.allPosts = res.data; }) .catch(error => console.log(error)); }, } } </script> We have imported
  • 18. 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
  • 19. <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>
  • 20. </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.
  • 21. 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. Now, let’s see the implementation of API using Axios in the service.js file. 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) –
  • 22. 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
  • 23. 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 { path: '/posts/:id', component: PostDetails }, <p class="title"> <router-link :to="'/posts/' + post.id" > Title - {{ post.title }} </router-link> </p>
  • 24. 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>
  • 25. </b-row> </div> <b-row> <b-col cols="12" class="commentTitle"> <h2 style="font-weight: 500">Comments</h2> </b-col> <base-comment :comments="allComments"></base- comment> </b-row> </b-container> <h3 v-else>Loading....</h3> </div> </template> <script> import { Service } from "../../service.js"; import baseComment from "../ui/BaseComment.vue";
  • 26. 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,
  • 27. }; 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>
  • 28. 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)); },
  • 29. – 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.
  • 30. <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>
  • 31. 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.
  • 32. { 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> router/index.js PageNotFound component will render whenever an invalid route hits. You can find the entire source code here: vue-router-example
  • 34. 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.