VueJs and API (Axios)- Part-1

Shubham Sharma
7 min readApr 23, 2020

--

In this VueJs series, We will cover the following points-

  • Basics of VueJs.
  • Fetch data from APIs and display it in UI.
  • Understanding of components “ Generic Components”.
  • Debug javascript code using Chrome Developer tools.

What is VueJs?

It’s a Javascript library, focuses on the view layer, easy to pick up and integrate with other libraries or existing projects. On the other hand, Vue is perfectly capable of powering sophisticated Single-Page Applications, when using a combination of modern tooling and supporting libraries.

Primarily we have to install VueJs in our machine.

Installation of VueJs

Pre-requisites for vue.js-

  1. Visual Studio Code- (https://code.visualstudio.com/)
  2. NodeJs (stable release)- https://nodejs.org/en/download/

After installing these 2, we can proceed towards the set-up of VueJs (using npm)- https://vuejs.org/v2/guide/installation.html Then We have to configure Vue-Cli in our machine for rapid VueJs Development. We can install it by using the npm command.

npm install -g @vue/cli

First VueJs Project:

Create a folder in your system and then open it to your editor. After that run the below command in terminal-

vue create .

this command will setup the vue.js project in the newly created folder (Please select the babel and eslint as a default preset), then do npm run serve and yaay, we have created our first VueJs project.

This is how our First Vue Project appear

Importance of main.js in Vue?

When we run a Vue JS application, have a basic HTML page (like index.html) as an entry point and for initialization of Vue app, imported main.js in the <script> on that same page. When we write a Vue JS application we can also choose to do it in pure JavaScript, in TypeScript or in the .vue component format which combines the HTML, CSS, and JavaScript you need to define components. The .vue format do not run directly , Firstly it has to be compiled into JavaScript by a packager like WebPack and then loaded by your entry point.

  1. App.vue- It’s typically the root component of your application in the Vue Component file format. It’s usually something that defines the template for your page.
  2. Main.js- It’s usually the JavaScript file that will initialize this root component into an element on your page. It is also responsible for setting up plugins and 3rd party components you may want to use in your app. (like here we have imported router)
import Vue from "vue";
import { store } from "./store/store";
import router from "./router";
import App from "./App.vue";

new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");

3. Index.html-

The index page provides your entry point in HTML, providing an element for VueJs to load into and imports main.js to initialize your app. <div> element with ‘id’ has been mounted in the Vue instance.

<!-- the html element that hosts the App.vue component -->
<div id="app"></div>

<!-- built files will be auto injected -->
<script type="text/javascript" src="main.js"></script>

after creating the first vue project, I will recommend you to install the following things-

  1. Vue.js dev-tools- It is a chrome extension offered by the vue.js community which is useful while debugging our vue.js code.
  2. Vetur- It is Vue tooling for Visual Studio code and very helpful while writing code in the editor as it will give syntax-highlighting, snippet, formatting, auto-completion, etc. this extension will be available in visual studio code (File → Preferences → Extensions).
  3. Code Runner- It is an awesome extension for running the code in editor itself e.g. C, C++, Java, JavaScript, PHP, Python, Perl, Perl 6, Ruby, Go, Lua, Groovy, PowerShell, BAT/CMD, BASH/SH, F# Script, F# (.NET Core), C# Script, C# (.NET Core), VBScript, TypeScript, CoffeeScript, Scala, Swift, Julia, Crystal, OCaml Script, R, AppleScript, Elixir, Visual Basic .NET, Clojure, Haxe, Objective-C, Rust, Racket, Scheme, AutoHotkey, AutoIt, Kotlin, Dart, Free Pascal, Haskell, Nim, D, Lisp, Kit, V, SCSS, Sass, CUDA. It supports these languages.

What are the components in VueJs?

In this section, I will give you a basic understanding of components, e.g. Component’s structure, how to import and use it, etc. Components are reusable blocks of code that can have both structure and functionality. It can help to create a more modular and maintainable codebase. This section will give you a brief understanding of the Single file Vue component (SFC). So basically it consists of mainly three sections-

  • Template
  • Script
  • Style

Template Section- The template section is where you put your HTML markup code along with any data variables or computed properties that are defined in the script section of the code.

You should watch out if your HTML markup is getting here too long, then it is usually a sign that you are doing too many things and you must consider creating a child component for that additional functionality.

Script Section- In the script section, you can define any local data, props, computed properties, watchers, methods, Vue lifecycle hooks along with the registration of any child component as needed. (P.S. I will cover vue life-cycle hooks in the separate blog).

Style Section- Finally, the style section allows you to define your component styles to make it presentable using normal CSS or by using Less, SCSS pre-processors, etc.

Since vue allows an incremental building of user interface, we can easily create small child components and use it to build a composite user interface. Now, I am going to create one child component and tell you, how to import that child component into the parent component.

  1. If you have included vue in your HTML file with script tag without using npm or if you are using any online text editors e.g. Codepen, jsfiddle then you should register the child component globally with vue and then you can use it anywhere in your HTML file.
// Parent component
<div id="app">
<!-- Child component coming right up -->
<basic-header></basic-header>
</div>

// Child component template
<script id="basic-header-template" type="text/template">
<div>
<h1>I am child component</h1>
</div>
</script>
// In script file
Vue.component('basic-header', {
template: '#basic-header-template'
})

// Parent component which will be mounted
// on DOM element with id app


new Vue({
/* The element to mount vue component */
el: "#app"
})

2). If you are using Vue-cli then below is the syntax for registering the child component to parent component. (I have created one example on code sandbox).

Props

In this section, we can define the variables which can be passed to child components from the parent component. Basically It is used for communication between Parent Component and Child Component.

There are two ways to define properties (in Array format or in Object Format).

// Array format to define component properties

props: ["data", "headers"]
// Object format to define component properties

props: {
data: {
type: Array,
default: true
},
headers: {
type: Array,
default: true
}
}

Sharing a demo of communication between Parent to Child.

//Parent Component<template>
<div id="app">
<HelloWorld :msg="title" />
</div>
</template>
<script>
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld
},
data(){
return {
title: 'Message coming from Parent'
}
}
};
</script>
// Child Component
<template>
<div>
<p>{{msg}}</p>
<input type="text" v-model="comp">
<span>{{comp}}</span>
</div>
</template>
<script>
export default {
name: "HelloWorld",
props: {
msg: String
},
data() {
return {
comp: "Enter Child Name"
};
}};
</script>

In this, I have taken Parent Component as App.vue and Child Component as Helloworld.vue and I took ‘title’ variable in parent component and passing this value to the child using props of Child Component.

Here, I took :msg as a props in Child Component and receiving the value of title (declared in parent component) in ‘msg’ of the child component.

Data

It acts as a local state of the component where we can define any variable to provide information to the component.

//inside component
data() {
return {
title: 'vue',
projectTitle: 'CRUD',
}
}

Methods

In this section, we can define methods or event handler associated with the HTML element.

Computed

By default, output of computed properties is cached by Vue but the output of methods is not cached. e.g I have made the computed property ‘calculate’, and I didn’t call this computed function , vue.js automatically invokes the function. let me explain these things using one example-

<template>
// Accesing this count which is computed function like variable in javasacript
<p>{{ calculate }}</p>
</template>

<script>
export default {
data() {
return {
arr: [1, 2, 3]
}
},
computed: {
calculate: function() {
return 'The calculated count is ' + this.arr.length * 10
}
}
}
</script>

You can see, I’m able to access this ‘calculate’ using its name only but if it was written under methods section then we can’t able to access this calculate method like a variable, we should have to call ‘calculate()’ like this. output of this calculate is internally cached until the arr data changes.

Important: computed properties are only updated when a reactive source updates. Regular JavaScript methods are not reactive, so a common example is to use Date.now():

<template>
<p>{{ now }}</p>
</template>

<script>
export default {
computed: {
now: function () {
return Date.now()
}
}
}
</script>

It will render once, and then it will not be updated even when the component re-renders. Just on a page refresh, when the Vue component is quit and reinitialized.

In this case, a method is better suited for your needs.

Thanks, We will meet soon on next part.

--

--

Shubham Sharma

Software Engineer-2 @ Dell R&D Center, Bengaluru (Indian Institute of Information Technology & Management, Gwalior)