zishu's blog

zishu's blog

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

在 vue 中使用 axios 調用數據

如何在 vue 中完成一次接口的調用?首選就是 axios,方便快捷又好用,支持各種 api , 封裝也很方便。

先用 node 安裝一下。

npm install axios

然後在 main.js 文件中引入。

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)

以我的一個工程目錄作為實例,看一下代碼。

// ListThere.vue

// html 代碼
...
<div>{{ info }}</div>
...

// js 代碼
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))
  },
};

數據成功的被取到,然後需要將它在頁面中展示出來。使用 vue 自帶的 v-for 列表渲染。

<ul class="list-api-show">
  <li v-for="(item, index) in show" :key="index">
    {{ item.title }}
  </li>
</ul>

然後通過 axios 把數據指向 v-for.

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

數據成功取出然後展示在 v-for 裡面。

當然了,這是成功的情況,加入失敗了呢?我們需要瀏覽器給出提示,所以 axios 給出了一個 api --- err 語法

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')
    });
}

如果接口有問題,或者我們調用時代碼寫錯了,都會給出報錯提示,具體什麼樣的錯誤會有什麼樣的警告,需要我們一一去經歷摸索。

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。