axios的安装和使用
安装
npm install axios
引入
在main.js中引入或者在封装的js里引入
import Axios from 'axios'
Vue.prototype.$axios=Axios
使用
get请求下面两种都可以:
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
或者
// 上面的请求也可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
post请求:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
页面如果觉得直接这样写有点low,也可以自己封装httpRequest.js
封装
1.httpRequest,js:
import axios from 'axios';
import qs from 'qs'//这个只要安装了axios就可以直接引入
var http = axios.create({
baseURL: '/api',
timeout: 1000
});
axios.defaults.headers.post['Content-Type']='application/x-www=-form-urlencoded'
http.param=(data = {},contentType = 'application/x-www-form-urlencoded')=>{
return contentType === 'application/x-www-form-urlencoded' ? qs.stringify(data):(contentType ==='application/json'?JSON.stringify(data):data);
}
/**
* get封装
* @params:url
* @params:params
*/
export function httpGet(url,param={}){
return new Promise((resolve,reject)=>{
http.get(url,{params:http.param(param)})
.then(response=>{
resolve(response.data)
})
.catch(err=>{
reject(err)
})
})
}
/**
* post封装
* @params:url
* @params:param
*/
export function httpPost(url,param={}){
return new Promise((resolve,reject)=>{
http.post(url,http.param(param))
.then(response=>{
resolve(response.data)
})
.catch(err=>{
reject(err)
})
})
}
2.main.js引入
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import axios from 'axios'
import {httpGet,httpPost} from '@/assets/utils/httpRequest.js'
Vue.config.productionTip = false
Vue.prototype.$axios=axios
Vue.prototype.$httpGet=httpGet
Vue.prototype.$httpPost=httpPost
/* eslint-disable no-new */
new Vue({
el: '#app',
components: { App },
template: '<App/>'
})
3.页面组件中就可以用了
getList(){
this.$httpGet('/ams-wangqin/userInfo/queryUserInfoListByParams',{userName:this.input})
.then(res=>{
console.log(res)
this.tableData=res;
})
.catch(err=>{
console.log(err)
})
}