Hi guys, this is a small tutorial for use Axios to call API with Vue CLI.
First step install Axios with command:
npm install --save axios vue-axios
Second step entry file into your main.js file:
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
After this, you only need your API link, Axios, and methods you want to call.
You have 2 ways for call axios on your file Vue:
You can use Axios with import on your file Vue like this:
<script>
import axios from 'axios';
//Use **mounted** if you want to print it on the screen.
mounted() {
AXIOS CALL
}
//Use **methods** if you have @click function.
methods(){
click() {
AXIOS CALL
}
}
</script>
Or simply add this before your Axios call like this:
<script>
this.axios.get()....
</script>
Now you can call your requests:
GET
(All)
axios.get("Api link" , {
headers: {
'Authorization': 'Bearer' + 'Your Bearer Pssword',
"Content-Type": "application/json",
}
})
.then(response => {
this.datas = response.data
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
GET
(Select by id one of this to show)
axios.get("Api link" , + id {
headers: {
'Authorization': 'Bearer' + 'Your Bearer Pssword',
"Content-Type": "application/json",
}
})
.then(response => {
this.datas = response.data
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
POST
(You need id and new formData for create new data; you take this from an input with specify v-model for your data)
var formData = new FormData()
formData.append('Your_database_column', this.Your_new_input_v-model)
axios.post("Api link", formData, {
headers: {
'Authorization': 'Bearer' + 'Your Bearer Pssword',
"Content-Type": "application/json",
}
})
.then(function(response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
},
}
PUT
(You need id and a formData for change the old value; you take this from an input with specify v-model for your edit data)
var formData = {
role: this.Your_edit_input_v-model,
}
axios.put("Api link" , + id, formData, {
headers: {
'Authorization': 'Bearer' + 'Your Bearer Pssword',
"Content-Type": "application/json",
}
})
.then(response => {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
DELETE
(You need the id for delete a data)
axios.delete("Api Link" + id, {
headers: {
'Authorization': 'Bearer '+ 'Your Bearer Pssword',
"Content-Type": "application/json",
}
})
.then(function(response){
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
}
Thanks for reading my first #dev post!
Top comments (1)
This blog is about VueAxios but you used only Axios.