我使用的是vue-cli+axios的組合,下面我想記錄一下如何在vue-cli中使用axios:
將終端移至項目目錄下,輸入
npm install axios
當出現如下圖時則表示axios已經下載成功:
在vue-cli目錄中的main.js中:加入以下兩行代碼:
import axios from 'axios'
Vue.prototype.$axios=axios;
添加到main.js的位置應如圖所示:
除此之外還可如圖中所示添加baseUrl:
this.$axios.defaults.baseURL='地址'
這樣就完成了在vue-cli中的配置
我們將一個完整的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調用,其中各參數爲:
以上是一個最簡單的請求實例,沒有發送數據,如果需要發送參數,則可以使用:
下面一個簡單的示例:
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
除此之外還有很多的參數可以添加,在這就不贅述了,各位可以去官網查看