1.get和delete请求,请求参数格式是query格式,参数是在url后通过**“&”**拼接
get请求,参数放在config中的params中
//接口全写请求: url地址?id=12121&name='huahua'
//或者直接拼接在接口中写axios.get("url地址?id=12121&name='huahua'")
axios.get('url地址', {
params: {
id: 12121,
name: 'huahua'
}
})
delete请求, 参数放在config中的data中
//接口全写请求: url地址?id=12121&name='huahua'
//或者直接拼接在接口中写axios.delete("url地址?id=12121&name='huahua'")
axios.delete('url地址', {
data: {
id: 12121,
name: 'huahua'
}
})
post请求, 参数放在第二个参数data中
axios.post('url地址', {
id: 12121,
name: 'huahua'
})
同时发生的请求 使用axios.all和axios.spread
同时发生的请求 使用axios.all和axios.spread
//axios.all([接口数组]).then(axios.spread( (接口返回数据) => {}))
mounted() {
axios.all([this.getListOne(), this.getListTwo()]).then(axios.spread((dataOne, dataTwo) => {
console.log(dataOne) //dataOne是接口getListOne返回的数据
console.log(dataTwo) //dataTwo是接口getListTwo返回的数据
}))
},
methods: {
getOneList() {
return axios.get('/getListOne')
},
getTwoList() {
return axios.get('/getListTwo')
},
}
采用 let param = new URLSearchParams()
把参数封装在param里面
param.append(‘username’, ‘admin’),
param.append(‘password’, ‘admin’) ,
sbt(){
let param = new URLSearchParams()
param.append('username', 'admin'),
param.append('password', 'admin') ,
this.axios({
method: "post",
url: '/api/PsychoSys/regedit.action',
data: param
})
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.log(err);
});
},
引入 qs ,这个库是 axios 里面包含的,不需要再下载了
sbt(){
let data = {
'username': 'ddd',
'password': '101010'
}
this.axios({
method: "post",
url: '/api/PsychoSys/regedit.action',
data: Qs.stringify(data)
})
.then(function(res) {
console.log(res);
})
.catch(function(err) {
console.log(err);
});
},
vue高版本中,推荐使用axios进行网络请求,而不再使用vue-resource。
在vue04项目中,在终端运行 npm install --save axios vue-axios
,下载vue-axios插件
注意:“vue04项目”是指我的上篇博客中通过vue-cli脚手架创建的项目(后面我会附上源码,博客标题:《利用vue-cli创建项目步骤简述》
提示:使用插件的时候,一般都要在入口文件main.js中引入,因为main.js项目运行首先运行的文件。具体代码如下:
main.js文件
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
疑问:为什么使用Vue.use(VueAxios, axios)
解惑:通过全局方法 Vue.use() 使用插件,就相当于调用install方法,vue官网举例如下:
// 调用 `MyPlugin.install(Vue)`
Vue.use(MyPlugin)
注意:在comunication组件中发起请求,要使用Vue,所以需要引入,即import vue from ‘vue’(comunication组件是本例中发起网络请求的组件)