vue之axios數據通信

Vue 使用axios數據通信

1、下載插件:(這裏下載命令有兩種)
1)npm install axios --save
(會在package.json中生成一個axios的一個選項,加上–save,如果項目中的 node_modules不小心刪除,二次下載node_modules的時候裏面會包括axios, 不需要再單獨下載)
2)npm install axios
(與上面相反)
2、導入插件:
在 main.js中導入插件
import axios from ‘axios’
Vue.prototype.$axios = axios
3、使用插件:
es5和es6兩種用法的區別:
Es5作用於會發生改變而Es5作用於不會發生改變,所以在給list賦值的時候,es6可以直接用this.list=response.data,而es5需要在使用之前記錄一下vue對象,所以在初始化的時候var that=this;that.list=response.data;

1)get請求數據

es6的寫法:

this.$axios.get(「http://127.0.0.1:8008/index/」,{
type:2
})
.then(response=>{
console.log(response.data); //後端返回的數據
this.list=response.data; //給list賦值
})
.catch(error=>{
console.log(error)
})
es5的寫法:

var that=this;
this.$axios.get(「http://127.0.0.1:8000/index/」,{
type:2
}).then(function(response){
console.log(response.data);
that.list=response.data;
}).catch(function(error){
console.log(error)
})

2)post請求數據
注意事項:
1.發送數據之前需要整理成鍵值對的形式
導入插件qs qs.stringify(data)
import qs from ‘qs’

2.後端 需要把中間件csrf註釋掉
var _data={
type:2
}
//封裝成key-vale
var _data1=qs.stringify(_data)
this.$axios({
method:「post」,
url: 'url,
data:_data1
}).then(response=>{
console.log(response.data)
}).catch(error=>{
console.log(error)
})
在這裏插入圖片描述