zishu's blog

zishu's blog

一个热爱生活的博主。https://zishu.me

Using axios to make data calls in Vue

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 the code using my project directory as an example.

// 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 we need to display it on the page. We can use the built-in v-for directive in Vue 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 the v-for directive.

mounted() {
  axios
    // ...
    .then((response) => (this.show = response.data.result.today))
}

The data is successfully retrieved and displayed within the v-for directive.

Of course, this is the case when everything goes smoothly. But what if there is an error? We need to provide feedback to the user, 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 a problem with the API or if we make a mistake in our code, an error message will be displayed. The specific warning depends on the type of error and requires us to explore and troubleshoot one by one.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.