How to make an API call in Vue? The preferred method is to use axios, which is convenient, fast, and easy to use. It supports various APIs and is also easy to encapsulate.
First, install it using Node.
npm install axios
Then, import it in the main.js file.
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
Let's take a look at an example using my project directory.
// ListThere.vue
// HTML code
...
<div>{{ info }}</div>
...
// JavaScript code
import axios from "axios";
export default {
name: "ListThere",
data() {
return {
...
};
},
components: {
...
},
methods: {
...
},
mounted() {
axios
.get("http://api.h-camel.com/api?mod=interview&ctr=issues&act=today")
.then((response) => (this.info = response))
},
};
The data is successfully retrieved and now needs to be displayed on the page. We can use Vue's built-in v-for
directive for list rendering.
<ul class="list-api-show">
<li v-for="(item, index) in show" :key="index">
{{ item.title }}
</li>
</ul>
Then, use axios to assign the data to v-for
.
mounted() {
axios
// ...
.then((response) => (this.show = response.data.result.today))
}
The data is successfully retrieved and displayed within the v-for
loop.
Of course, this is the case when everything goes smoothly. But what if there is an error? We need to provide a prompt to the browser, so axios provides an API called err syntax
.
mounted() {
axios
// ...
.catch(function (error) {
if (error.response) {
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
console.log('err')
} else if (error.request) {
console.log(error.request);
console.log('err')
} else {
console.log('Error', error.message);
console.log('err')
}
console.log(error.config);
console.log('err')
});
}
If there is an issue with the API or if we made a mistake in our code, it will give an error prompt. The specific type of error and the corresponding warning will require us to explore and troubleshoot one by one.