VueJS Framework
VueJS Framework
1. Application instance
Every Vue application starts by creating a new application instance with the createApp function:
An application instance won't render anything until its .mount() method is called. It expects a
"container" argument, which can either be an actual DOM element or a selector string:
<div id="app"></div>
app.mount('#app')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
{{hello}}
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
let app=Vue.createApp({
data:function(){
return{
hello:"hello world!"
}
}
})
app.mount('#app')
</script>
</body>
</html>
2. Directives and data binding
VueJS has built-in directives such as v-if, v-else, v-show, v-on, v-bind, and v-model, which are
used to perform various actions on the frontend.
Vue.js directives are special HTML attributes that tell Vue what to do with a DOM element. They
are usually prefixed with the v- symbol, and can be used to bind data, add event listeners, control
the rendering of elements and so much more.
Vue.js provides a variety of directives for different use cases. The most commonly used ones:
1. v-bind
The v-bind directive, often abbreviated as : , allows you to bind an attribute to an expression. It's
useful for dynamically setting HTML attributes, such as src or href.
<img v-bind:src="imageURL">
2. v-model
The v-model directive is used for two-way data binding. It binds an input element's value to a
variable, allowing changes in the input to update the variable, and vice versa.
3. v-for
The v-for directive is used for rendering lists of items. It iterates over an array and creates elements
for each item.
<ul>
These directives are used for conditional rendering. Here's how they work:
v-if: It displays an element only if a condition is true. If the condition is false, the element won't
be shown.
v-else-if: This directive allows us to set another condition in case the first one is false. It acts as a
backup condition.
v-else: If none of the previous conditions are met (v-if and v-else-if), v-else comes into play and
displays an element. It's like a "last resort" condition.
Together, these directives give us control over what appears on our webpage depending on
different situations and conditions.
5. v-on
The v-on directive, often abbreviated as @, is used to listen to DOM events and trigger methods
or expressions when those events occur.
6. v-show
The v-show directive is similar to v-if but toggles the element's visibility using
CSS display property, instead of adding/removing it from the DOM.
<p v-show="isVisible">This text can be hidden and shown.</p>
7. v-html
The v-html directive updates the element's innerHTML.This can be used in cases where data is in
an html format. Just be careful with the directive as it can lead to security threats. Make sure to
only use it to display trusted data!
<script setup>
</script>
<template>
<div v-html="message"></div>
</template>
8. v-once
The v-once directive renders the element/component once and only once. After the initial render,
this element and all of its children will be treated as static content.
This can be great for optimizing render performance in your Vue.js application.
<template>
</template>
9. v-memo
The v-memo directive in Vue.js memoizes a template sub-tree, storing previous render results to
accelerate future renders. It relies on a dependency array and re-renders only when values in the
array change, ensuring updates occur selectively based on specified dependencies. In essence, it
optimizes rendering by updating the sub-tree only when necessary.
<template>
</template>
10. v-cloak
The v-cloak directive can be used to hide uncompiled templates until the component is ready. This
may be necessary when building Vue.js applications using a CDN which contains a no-build step.
<div v-cloak>
{{ message }}
</div>
Data Binding
The data binding feature helps manipulate or assign values to HTML attributes, change the style,
assign classes with the help of binding directive called v-bind available with VueJS.
Interpolations
Text
The most basic form of data binding is text interpolation using the “Mustache” syntax (double
curly braces):
Ex1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
background-color: aqua;
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<div id="app">
{{hello}}
<input type="text" v-model="hello"/>
<hr>
<div v-if="isVisible" class="box"></div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
let app=Vue.createApp({
data:function(){
return{
hello:"hello world!",
isVisible:true
}
}
})
app.mount('#app')
</script>
</body>
</html>
Ex2:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
background-color: aqua;
height: 200px;
width: 200px;
}
.box1{
background-color: pink;
height: 200px;
width: 200px;
}
.box2{
background-color: green;
height: 200px;
width: 200px;
}
v-cloak{
display: none;
}
</style>
</head>
<body>
<div id="app" v-cloak>
{{hello}}
<input type="text" v-model="hello"/>
<hr>
<div v-if="isVisible" class="box"></div>
<div v-else-if="isVisible" class="box1"></div>
<div v-else="isVisible" class="box2"></div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
let app=Vue.createApp({
data:function(){
return{
hello:"hello world!",
isVisible:true
}
}
})
app.mount('#app')
</script>
</body>
</html>
<template>
<div class="box" v-for="item in countries" :key="item.id">
<h1>{{item.country}}</h1>
<p>{{item.capital}}</p>
</div>
</template>
<script>
export default{
name:"contactComponent",
data:function(){
return{
countries:[
{
country: 'Ghana',
capital: 'Accra'
},
{
country: 'Nigeria',
capital: 'Abuja'
},
{
country: 'England',
capital: 'London'
},
{
country: 'Spain',
capital: 'Madrid'
}
]
}
}
}
</script>
<style>
</style>
Vue v-model is a directive that creates a two-way data binding between a value in our template
and a value in our data properties, while v-bind only binds data one way. A common use case for
using v-model is when designing forms and inputs.
In our example 3, we bind the key for better working. We can use :key or v-bind:key.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
background-color: aqua;
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<div id="app" v-cloak>
{{hello}}
<input type="text" v-model="hello"/>
<hr>
<button v-on:click="isVisible=!isVisible">SHOW</button>
<div v-if="isVisible" class="box"></div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
let app=Vue.createApp({
data:function(){
return{
hello:"hello world!",
isVisible:false
}
}
})
app.mount('#app')
</script>
</body>
</html>
2. Methods
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
background-color: aqua;
height: 200px;
width: 200px;
}
</style>
</head>
<body>
<div id="app" v-cloak>
{{hello}}
<input type="text" v-model="hello"/>
<hr>
<button @click="toggleBox">Toggle</button>
<div v-if="isVisible" class="box"></div>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
let app=Vue.createApp({
data:function(){
return{
hello:"hello world!",
isVisible:false
}
},
methods:{
toggleBox(){
this.isVisible=!this.isVisible
}
}
})
app.mount('#app')
</script>
</body>
</html>
Unlike page templates, which also enable developers to reuse markup, custom components provide
more power and flexibility because:
1. Custom components allow developers to define attributes that can be passed in to each
component.
2. Custom component descriptions are displayed in the application's component reference
dialog alongside standard component descriptions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
input{
margin: auto;
}
</style>
</head>
<body>
<div id="app">
<login-form/>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
let app=Vue.createApp({ })
app.component('login-form',{
template:`
<form @submit.prevent="handleSubmit">
<h1>{{title}}</h1>
<custom-input type="email" v-bind:label="emailLabel" :mod-
elValue="email" v-model="email"/><br><br>
<custom-input type="password" :label="passwordLabel" :mod-
elValue="password" v-model="password"/><br><br>
<button>Login</button>
</form>
`,
components:['custom-input'],
data(){
return{
title:"Login Form",
email:"",
password:"",
emailLabel:'Email',
passwordLabel:'Password'
}
},
methods:{
handleSubmit(){
console.log(this.email,this.password);
}
}
})
app.component('custom-input',{
template:`
<label>
{{label}}
<input type="text" v-model="inputValue">
</label>
`,
props:['label','modelValue'],
computed:{
inputValue:{
get(){
return this.modelValue
},
set(value){
this.$emit("update:modelValue",value)
}
}
}
})
app.mount('#app')
</script>
</body>
</html>
5.Component Lifecycle
Vue follows a pattern when working with components, from their creation to their destruction
through data updates and DOM insertion.
1. Before create
2. Created
3. Before mount
4. Mounted
5. Before update
6. Updated
7. Before destroy
8. Destroyed
beforeCreate() hook: The beforeCreate() is the first event or hook that occurs in the creation
process. It facilitates developers to perform actions even before the component has been added to
the DOM. We cannot access the DOM inside of this event. In this hook, the data is still not reactive
and events that occur during the component's lifecycle have not been set up yet.
created() hook: The created() hook is used to run the code after creating the instance. It facilitates
you to access the reactive data, but the mounting or rendering of templates and Virtual DOM is
not completed yet. In this hook, events are active and access to reactive data is enabled though
templates have not yet been mounted or rendered.
beforeMount() hook: The beforeMount() hook is used to execute just before the initial render
happens and after the template or render functions have been compiled. It is invoked after the
template has been compiled and the virtual DOM updated by Vue. This is the rarely used event,
and in most cases, you don't need to use this event.
mounted() hook: The mounted() hook is the most frequently used event or hook. This hook
provides you full access to the reactive component, templates, and rendered DOM In this hook;
you have full access to the reactive component, templates, and rendered DOM.
beforeUpdate() hook: The beforeUpdate() hook is executed just before the data changes on the
component and the update cycle's start. It runs right before the DOM is patched and re-rendered.
updated() hook: The updated() hook is used to execute after the data changes on the component
and the DOM re-renders. If you want to access the DOM after a property change, it is the best
place to complete this action.
beforeDestroy() hook: The beforeDestroy() hook is used to execute just before tearing down the
instance. This is the second last step of the Vue Instance life process and is the right place to clean
up events or reactive subscriptions if you have to do this.
destroyed() hook: The destroyed() hook is the last step of the Vue.js Instance life process and
used to do any last minute clean up.
Here is the complete diagram:
<template>
<div id="app">
<h1>Welcome</h1>
<home/>
</div>
</template>
<script>
import home from './components/home.vue'
export default {
name:'App',
components:{
home
}
}
</script>
Home.vue
<template>
<div>
<h1>{{name}}</h1>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
name:"CELESTIN"
}
},
created(){
console.warn("created",this.name)
},
beforeCreate(){
console.warn("before create",this.name)
}
}
</script>
Example2:
<template>
<div>
<h1>{{name}}</h1>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
name:"CELESTIN"
}
},
created(){
this.name="Bella"
console.warn("created",this.name)
},
beforeCreate(){
console.warn("before create",this.name)
}
}
</script>
Example3:
<template>
<div>
<h1>{{name}}</h1>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
name:"CELESTIN"
}
},
created(){
this.name="Alice"
console.warn("created",this.name)
},
beforeCreate(){
this.name="Madame"
console.warn("before create",this.name)
}
}
</script>
<template>
<div>
<h1>{{name}}</h1>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
name:"CELESTIN"
}
},
mounted(){
console.warn("mounted")
},
beforeMount(){
console.warn("before mounted")
}
}
</script>
Example5:
<template>
<div>
<h1>{{name}}</h1>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
name:"CELESTIN"
}
},
mounted(){
console.warn("mounted",this.$el)
},
beforeMount(){
console.warn("before mounted",this.$el)
}
}
</script>
Example6:
<template>
<div>
<h1 id="mount">{{name}}</h1>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
name:"CELESTIN"
}
},
mounted(){
console.warn("mounted",document.getElementById("mount"));
},
beforeMount(){
console.warn("before mounted",document.getElementById("mount"));
}
}
</script>
3. beforeUnmount() and unmounted()
Example7:
app.vue
<template>
<div id="app">
<div v-if="display">
<home />
</div>
<button v-on:click="toggle">Toggle</button>
</div>
</template>
<script>
import home from './components/home.vue'
export default {
name:'App',
components:{
home
},
data(){
return{display:true}
},
methods:{
toggle()
{
this.display=!this.display;
}
}
};
</script>
Home.vue
<template>
<div>
<h1>{{name}}</h1>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
name:"CELESTIN"
}
},
beforeUnmount(){
alert("beforeDestroy method called")
},
unmounted(){
alert("destroyed method called")
}
}
</script>
Transition VueJS provides various ways to apply transition to the HTML elements when they are
added/updated in the DOM. VueJS has a built-in transition component that needs to be wrapped
around the element , which needs transition.
v-enter: This class is called initially before the element is updated/added. Its the starting state.
v-enter-active: This class is used to define the delay, duration, and easing curve for entering in
the transition phase. This is the active state for entire and the class is available during the entire
entering phase.
v-leave-active: Applied during the leaving phase. It is removed when the transition is done. This
class is used to apply the delay, duration, and easing curve during the leaving phase.
Animations are applied the same way as transition is done. Animation also has classes that needs
to be declared for the effect to take place. To apply animation, there are classes same as transition.
Example:
<template>
<div class="container">
<div class="row">
<div class="col">
<h2>Jesus I trust in you</h2>
<img src="@/assets/13.jpg" width="100px">
</div>
<div class="col">
<button class="btn btn-warning" @click="show=!show">SHOW</button>
<transition name="fade">
<p v-show="show"><img src="@/assets/14.jpg" class="m-2"
width="100px">Animation</p>
</transition>
</div>
<div class="col">
<button class="btn btn-warning" @click="show=!show">SHOW</button>
<transition name="data">
<p v-show="show"> <img src="@/assets/13.jpg" class="m-2"
width="80px">Animation of image</p>
</transition>
</div>
</div>
</div>
</template>
<script>
export default{
name:"homeComponent",
data:function(){
return{
show:true
}
}
}
</script>
<style scoped>
.fade-enter-active{
animation:shift-in 2s;
}
.fade-leave-active{
animation:shift-in 2s reverse;
}
@keyframes shift-in{
0%{transform: rotateX(0deg);}
25%{transform: rotateX(90deg);}
50%{transform: rotateX(120deg);}
75%{transform: rotateX(180deg);}
100%{transform: rotateX(360deg);}
}
.data-enter-active, .data-leave-active{
transition:all 2s ease-in-out;
}
.data-enter, .data-leave-to{
transform: translateX(100px);
}
</style>
8. Watchers
The Vue.js Watcher or watch property allows the developers to listen to the component data and
run whenever they change a particular property. The watcher or watch property is a unique Vue.js
feature that lets you keep an eye on one property of the component state and run a function when
that property value changes.
App.vue
<template>
<home />
</template>
<script>
import home from "./components/home.vue"
export default {
name:'App',
components:{
home
}
}
</script>
Home.vue
<template>
<div>
<h1>{{count}}</h1>
<button v-on:click="count=count+1">ADD</button>
<button v-on:click="count=count-1">REMOVE</button>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
count:0
}
},
watch:{
count(val,prev){
if(val>8 && val>prev){
// alert("stop")
this.count=0
}
}
}
}
</script>
9. Computed property
In-template expressions are very convenient, but they are meant for simple operations. Putting
too much logic in your templates can make them bloated and hard to maintain.
We use computed property when we have very large and complex logic. When we have to print
very simple data, then we can use template expression.
Example1:
app.vue
<template>
<div id="app">
<home />
</div>
</template>
<script>
import home from './components/home.vue'
export default {
name:'App',
components:{
home
}
}
</script>
Home.vue
<template>
<div>
<h1>Computed property {{dollar}}</h1>
<h2>{{getData}}</h2>
</div>
</template>
<script>
export default {
name:'home',
data(){
return{
dollar:200,
indian:100,
discout:50
}
},
computed:{
getData(){
return ((this.dollar*this.indian)-this.discout)
}
}
}
</script>
Example2:
<template>
<div id="app">
<fieldset>
<h1>Currency Converter Application</h1>
<Span>Enter Amount:</Span>
<input type="text" v-model.number="amount" placeholder="enter
amount"><br><br>
<Span>Convert From:</Span>
<select v-model="convertfrom">
<option v-for="a in currencyfrom" v-bind:value="a.name"
:key="a.name">{{a.desc}}</option>
</select>
<Span>Convert To:</Span>
<select v-model="convertto">
<option v-for="a in currencyfrom" v-bind:value="a.name"
:key="a.name">{{a.desc}}</option>
</select><br><br>
</fieldset>
</div>
</template>
<script>
export default{
name:"currencyConverter",
data:function(){
return{
name:"",
currencyfrom:[
{name:"USD",desc:"US Dollar"},
{name:"EUR",desc:"EURO"},
{name:"INR",desc:"Indian roupe"},
{name:"BHD",desc:"Dinar"}
],
convertfrom:"INR",
convertto:"USD",
amount:""
}
},
computed:{
finalamount:function(){
var to=this.convertto;
var from=this.convertfrom;
var final;
switch(from){
case "INR":
if(to=="USD"){
final=this.amount*0.006;
}
if(to=="EUR"){
final=this.amount*0.006;
}
if(to=="INR"){
final=this.amount;
}
if(to=="BHD"){
final=this.amount*0.0059;
}
break;
case "USD":
if(to=="USD"){
final=this.amount;
}
if(to=="EUR"){
final=this.amount*0.84;
}
if(to=="INR"){
final=this.amount*63.88;
}
if(to=="BHD"){
final=this.amount*0.38;
}
break;
case "EUR":
if(to=="USD"){
final=this.amount*1.19;
}
if(to=="EUR"){
final=this.amount;
}
if(to=="INR"){
final=this.amount*76.25;
}
if(to=="BHD"){
final=this.amount*0.45;
}
break;
case "BHD":
if(to=="USD"){
final=this.amount*2.65;
}
if(to=="EUR"){
final=this.amount*2.22;
}
if(to=="INR"){
final=this.amount*168.23;
}
if(to=="BHD"){
final=this.amount;
}
break;
}
return final;
}
}
}
</script>
<style scoped>
fieldset{
width: 60%;
margin: 50px;
padding: 20px;
border-radius: 8px;
box-shadow: 4px 7px 9px green;
}
</style>
10. Routing
Routing on the server side means the server sending a response based on the URL path that the
user is visiting.
When we click on a link in a traditional server-rendered web app, the browser receives an
HTML response from the server and reloads the entire page with the new HTML.
In a Single-Page Application (SPA), however, the client-side JavaScript can intercept the
navigation, dynamically fetch new data, and update the current page without full page reloads.
In such SPAs, the "routing" is done on the client side, in the browser. A client -side router is
responsible for managing the application's rendered view using browser APIs such as History
API.
To use it, we first install vue-router in your project by using npm install vue-router@next
command in terminal.
We create a new JavaScript file routes.js from src.
const routes = [
{
name: "home",
path: "/",
component: home
},
{
name: "login",
path: "/login",
component: login
},
{
name: "profile",
path: "/profile",
component: profile
}
];
profile.vue
<template>
<div>
<h1>This is profile</h1>
</div>
</template>
<script>
export default {
name:'profile',
}
</script>
Login.vue
<template>
<div>
<h1>Welcome to login</h1>
</div>
</template>
<script>
export default {
name:'login',
}
</script>
Home.vue
<template>
<div>
<h1>Home</h1>
</div>
</template>
<script>
export default {
name:'home',
}
</script>
App.vue
<template>
<div id="app">
<home />
</div>
</template>
<script>
import home from './components/home.vue'
export default {
name:'App',
components:{
home
}
}
</script>
Output:
Home
<template>
</template>
<script>
export default {
name:'App',
}
</script>
No output
<template>
<router-view></router-view>
</template>
<script>
export default {
name:'App',
}
</script>
Output:
Home
Output:
Welcome to login
<template>
<router-link to="/">Home</router-link><br>
<router-link to="/login">Login</router-link><br>
<router-link to="/profile">Profile</router-link>
<router-view></router-view> <!-- or <router-view /> -->
</template>
<script>
export default {
name:'App',
}
</script>
Output:
Dynamic Routing
App.vue
<template>
<router-link to="/">Home</router-link><br>
<router-link to="/login">Login</router-link><br>
<router-link to="/profile/john">John Profile</router-link><br>
<router-link to="/profile/kim">Kim Profile</router-link><br>
<router-link to="/profile/Putin">Putin Profile</router-link>
<router-view></router-view> <!-- or <router-view /> -->
</template>
<script>
export default {
name:'App',
}
</script>
const routes = [
{
name: "home",
path: "/",
component: home
},
{
name: "login",
path: "/login",
component: login
},
{
name: "profile",
path: "/profile/:name",
component: profile
}
];
<template>
<div>
<h1>This is{{profile}} 's profile</h1>
</div>
</template>
<script>
import {useRoute} from 'vue-router'
export default {
name:'profile',
data(){
return{
profile:""
}
},
mounted(){
const route=useRoute();
console.log("Route", route.params.name)
this.profile=route.params.name
}
}
</script>
Output:
API
API stands for Application Programming Interface. Interface for sharing data between two
applications.
There are different methods to use with API, like: GET, POST, DELETE, PUT, etc.
We can test API with POSTMAN or INSOMNIA. You can go on google and search for
POSTMAN or INSOMNIA.
Example for testing: https://jsonplaceholder.typecode.com/todos with GET method.
API endpoint
An API endpoint is a point at which an API, the code that allows two software programs to com-
municate with each other, connects with the software program. APIs work by sending requests for
information from a web application on web server and receiving a response.
In other words, API endpoints are the specific digital location where requests for information are
sent by one program to retrieve the digital resource that exists there. Endpoints specify where APIs
can access resources and help guarantee the proper functioning of the incorporated software. An
API's performance depends on its capacity to successfully communicate with API endpoints.
Systems that communicate through APIs are integrated systems. One side sends the information
to the API and is called the server. The other side, the client, makes the requests and manipulates
the API. The server side that provides the requested information, or resources, is the API endpoint.
Use API
Home.html
<center>
<div id="api">
<img v-bind:src="picture" alt="">
<h1>{{firstname}} {{lastname}}</h1>
<h3>Email:{{email}}</h3>
</div>
</center>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="home.js"></script>
Home.js
const app=Vue.createApp({
data(){
return{
firstname:"John",
lastname:"DODO",
email:"[email protected]",
picture:"https://randomuser.me/api/portraits/men/10.jpg"
}
}
})
app.mount("#api")
Output:
Home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="home.css">
</head>
<body>
<center>
<div id="api">
<img :class="gender" v-bind:src="picture" v-bind:alt="`$firstname
$lastname`">
<h1>{{firstname}} {{lastname}}</h1>
<h3>Email:{{email}}</h3>
<button v-on:click="getUser()" :class="gender" style="background-color:
rgb(68, 65, 65); color: aquamarine;border-radius: 5px;">Get User</button>
</div>
</center>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script src="home.js"></script>
</body>
</html>
Home.js
const app=Vue.createApp({
data(){
return{
firstname:"John",
lastname:"DODO",
email:"[email protected]",
gender:"male",
picture:"https://randomuser.me/api/portraits/men/10.jpg"
}
},
methods:{
getUser(){
console.log(this.firstname)
}
}
})
app.mount("#api")
home.css
.male{
background-color: aqua;
border-color: aqua;
}
.female{
background-color: pink;
border-color: pink;
}
button{
cursor: pointer;
}
img{
border-radius: 50%;
border: 5px #333 solid;
}
Output:
Home.js
const app=Vue.createApp({
data(){
return{
firstname:"John",
lastname:"DODO",
email:"[email protected]",
gender:"male",
picture:"https://randomuser.me/api/portraits/men/10.jpg"
}
},
methods:{
getUser(){
this.firstname="Sam"
this.lastname="DODO"
this.email="[email protected]"
this.gender="female"
this.picture="https://randomuser.me/api/portraits/women/10.jpg"
}
}
})
app.mount("#api")
home.js
const app=Vue.createApp({
data(){
return{
firstname:"John",
lastname:"DODO",
email:"[email protected]",
gender:"male",
picture:"https://randomuser.me/api/portraits/men/10.jpg"
}
},
methods:{
async getUser(){
const res=await fetch("https://randomuser.me/api")
const data=await res.json()
console.log(data)
this.firstname="Sam"
this.lastname="DODO"
this.email="[email protected]"
this.gender="female"
this.picture="https://randomuser.me/api/portraits/women/10.jpg"
}
}
})
app.mount("#api")
home.js
const app=Vue.createApp({
data(){
return{
firstname:"John",
lastname:"DODO",
email:"[email protected]",
gender:"male",
picture:"https://randomuser.me/api/portraits/men/10.jpg"
}
},
methods:{
async getUser(){
const res=await fetch("https://randomuser.me/api")
const {results} =await res.json()
//console.log(results)
this.firstname=results[0].name.first
this.lastname=results[0].name.last
this.email=results[0].email
this.gender=results[0].gender
this.picture=results[0].picture.large
}
}
})
app.mount("#api")
Output:
What is Axios?
Axios is a simple promise based HTTP client for the browser and nodeJS. It provides a simple to
use library in a small package with a very extensible interface.
1. With axios.get()
Example:
<template>
<table border="1">
<tr>
<th>#</th><th>Title</th><th>Description</th>
</tr>
<tr v-for="post in posts" :key="post.id">
<td>{{ post.id }}</td><td>{{ post.title }}</td><td>{{ post.body }}</td>
</tr>
</table>
</template>
<script>
import axios from "axios";
export default{
name:"ApiComponent",
data:function(){
return{
posts:[]
}
},
mounted(){
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response=>this.posts=response.data);
}
}
</script>
<style>
</style>
2. With axios.post()
Example1:
<template>
<div></div>
</template>
<script>
import axios from "axios";
export default{
mounted(){
axios.post('https://jsonplaceholder.typicode.com/posts',{
userId:'1',
title:'title',
body:'this is title'
})
.then(response=>console.log(response.data))
}
}
</script>
<style>
</style>
Example2:
<template>
<div class="container">
<div class="row">
<div class="col-md-6">
<form @submit.prevent="createPost()">
<div class="form-group">
UserId:<input type="text" id="id" class="form-control" v-
model="postData.userId">
</div>
<div class="form-group">
Title:<input type="text" id="title" class="form-control" v-
model="postData.title">
</div>
<div class="form-group mt-3">
Body:<textarea name="body" id="body" cols="30" rows="2" v-
model="postData.body"></textarea>
</div>
<button class="btn btn-primary mt-3">Create</button>
</form>
</div>
</div>
</div>
</template>
<script>
import axios from "axios";
export default{
name:"ApiComponent",
data:function(){
return{
postData:{userId:'',title:'',body:''}
}
},
methods:{
createPost(){
axios.post('https://jsonplaceholder.typicode.com/posts/1')
.then(response=>console.log(response.data))
}
}
}
</script>
<style>
</style>
3. With axios.put()
Example:
<template>
<div></div>
</template>
<script>
import axios from "axios";
export default{
mounted(){
axios.put('https://jsonplaceholder.typicode.com/posts/1',{
id:'1',
userId:'1',
title:'title',
body:'body'
})
.then(response=>console.log(response.data));
}
}
</script>
<style>
</style>
4. With axios.patch()
Example:
<template>
<div></div>
</template>
<script>
import axios from "axios";
export default{
mounted(){
axios.patch('https://jsonplaceholder.typicode.com/posts/1',{
title:'title'
})
.then(response=>console.log(response.data));
}
}
</script>
<style>
</style>
5. With axios.delete()
Example:
<template>
<div></div>
</template>
<script>
import axios from "axios";
export default{
mounted(){
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(response=>console.log(response.data));
}
}
</script>
<style>
</style>