記在使用vue-cli中使用axios的心得

我使用的是vue-cli+axios的組合,下面我想記錄一下如何在vue-cli中使用axios:

1.使用NPM安裝axios並進行配置

首先利用npm進行安裝

將終端移至項目目錄下,輸入

npm install axios

當出現如下圖時則表示axios已經下載成功:

安裝axios成功

接下來配置axios:

在vue-cli目錄中的main.js中:加入以下兩行代碼:

import axios from 'axios'
Vue.prototype.$axios=axios;

添加到main.js的位置應如圖所示:

添加配置

除此之外還可如圖中所示添加baseUrl:

this.$axios.defaults.baseURL='地址'

這樣就完成了在vue-cli中的配置

使用axios向後端發送請求

我們將一個完整的axios寫在某個組件的created()函數中:

let _this=this;
    this.$axios({
      method:'get',
      url:'/MainPage/listAllSorts'
    }).then(function (response) {
      _this.$data.typeInfo=response.data;
    }).catch((function (error) {
      console.log(error.response.data);
    }));

在vue-cli中用此方法使用axios,首先要用this.$axios調用,其中各參數爲:

  1. method是發送請求的類型,包括'get'、'post'、‘put’、‘delete’,
  2. url是請求的地址,如果設置了前面的baseURL屬性,則可以基於設置的url填寫
  3. .then(function(response))用來處理請求後的後端返回,其中response代表返回的請求信息,可以對它任意命名
  4. .catch(function(error))用以處理請求出錯的錯誤返回,其中error代表返回的錯誤的信息,也可任意命名

以上是一個最簡單的請求實例,沒有發送數據,如果需要發送參數,則可以使用:

  1. data:{}用以向後端發送json數據
  2. params:{}用以向後端發送合併在url上的數據

下面一個簡單的示例:

let _this=this;
    this.$axios({
      method:'get',
      url:'/MainPage/listAllSorts',
      data:{
        key:1231
      }
    }).then(function (response) {
      _this.$data.typeInfo=response.data;
    }).catch((function (error) {
      console.log(error.response.data);
    }));

在這個例子中key是以json的方式傳給後端

let _this=this;
    this.$axios({
      method:'get',
      url:'/MainPage/listAllSorts',
      params:{
        key:1231
      }
    }).then(function (response) {
      _this.$data.typeInfo=response.data;
    }).catch((function (error) {
      console.log(error.response.data);
    }));

此例中key被標識在url上,相當於:

http://基地址/MainPage/listAllSorts?key=1231

除此之外還有很多的參數可以添加,在這就不贅述了,各位可以去官網查看