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)
})
在这里插入图片描述