axios的使用方法
axios({
url:"http://",
method:'get/post/put/delete'默認是get
}).then(res=>console.log(res))
axios({
url:"http://",
專門針對get請求的參數拼接(?type=pop&page=1)
params:{
type:'pop',
page:'1'
}
method:'get/post/put/delete'默認是get
})
也可以是axios.get() .post() .delete() .put()
axios的並發請求
axios.all([
axios({
url:"https://www.baidu.com"
}),
axios({
url:"https://www.baidu.com",
params:{
type:'pop',
page:'2'
}
}),
]).then(results=>{
console.log(result[0])
})/////
then(axios.spread(result1,result2)=>{
console.log(result1)///
})
全局配置
axios.defaults.baseURL='123.207.32.32.8000'
axios.defaults.headers.post['Content-Type']='application/x-www-form-urlencoded'
axios.defaults.timeout=5000
創建實例
每個實例都可以有自己的配置,相互不干擾
const instance=axios.create({
baseURL:'https://www.baidu.com',
timeout:5000,
headers:{}
})
instance({
url:'/home/data',
params:{
type:'pop',
page:'2'
}
}).then(res=>console.log(res))
封裝網絡模塊
request.js
axios使用promise()對網絡請求進行封裝
正常情況下在data里面都有做了定義
在函數里面進行賦值
這時候你運行時會發現,數據可以請求到,但是會報錯 TypeError: Cannot set property 'listgroup' of undefined
主要原因是:
在 then
的內部不能使用Vue的實例化的this
, 因為在內部 this
沒有被綁定。
可以看下 Stackoverflow 的解釋:
解決辦法:
1、用ES6箭頭函數,箭頭方法可以和父方法共享變量
2、在請求axios外面定義一下 var that=this
https://www.apiopen.top/api.html#4c502eec73ce429fb1c4a7f519360d24
dev: `webpack-dev-server --inline --progress --config build/webpack.dev.conf.js` vue啟動報錯解決
這是因為webpack-dev-server版本和vue版本不一樣,需要將webpack-dev-server卸載了,安裝對應版本
查看vue版本是 vue -V
注意:V是大寫
卸載npm uninstall webpack-dev-server
,在安裝這個npm i webpack-dev-server@2.9.7
,我的可以正常啟動了。