第一步安装:npm install --save axios
第二步:创建一个api.js 文件
import axios from 'axios';
axios.defaults.timeout = 30000;
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
//可以写if判断,提前拦截错误信息
return response;
}, function (err) {
return Promise.reject(err);
});
export function apiGet(url, params){
return new Promise((resolve, reject) =>{
axios.get(url, {
params: params,
headers:{"token":sessionStorage.getItem('token')}
}).then(res => {
resolve(res.data);
}).catch(err =>{
reject(err.data)
})
});
}
export function apiPost(url, params){
return new Promise((resolve, reject) => {
axios({
method: 'post',
url:url,
data:params
}).then(res => {
resolve(res.data);
}).catch(err =>{reject(err.data)})
});
}
第三步:创建一个http.js文件
import { apiGet, apiPost } from "./api";
//get请求
export const getVercode = query => {
return new Promise((resolve, reject) => {
apiGet('url地址', query).then(res => {
resolve(res)
}).catch(err => {
reject(err.data)
})
})
}
//post请求
export const getLogin = query => {
return new Promise((resolve, reject) => {
apiPost('url地址', query).then(res => {
resolve(res)
}).catch(err => {
reject(err.data)
})
})
}
第四步:在页面中引入并使用
import { getVercode, getLogin } from "../../api/http";
export default {
data() {
return {};
},
methods: {
getCode() {
getVercode().then((res) => {
if (res.code == 0) {
this.code = res.msg;
}
});
},
login() {
let obj = {
name: this.name,
pwd: this.pwd,
vercode: this.vercode,
};
getLogin(obj).then((res) => {
if (res.code == 0) {
this.$message.success("登陆成功");
this.$router.push("/home");
}
});
},
},
};