文件结构:
1.在api文件夹里面新建文件 https.js 进行请求封装
// 区分开发环境和生产环境 接口地址
const baseUrl = 'https://test/'; //这里要改成你的接口地址
export function https(config) {
//显示loading
wx.showLoading({
title: '加载中...'
});
//设置请求头
config.header = {
'content-type': 'application/json',
};
//检查缓存中有没有token
const token = uni.getStorageSync('graduateToken');
if (token) {
config.header.Authorization = token
// let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
// let curRoute = routes[routes.length - 1].route //获取当前页面路由
// if (routes == 'pages/login/login') {
// uni.switchTab({
// url: '../index/index',
// });
// }
} else {
uni.redirectTo({
url: '/pages/login/login.vue'
})
}
config.url = baseUrl + config.url; // 请求地址
let promise = new Promise(function(resolve, reject) {
uni.request(config).then(res => {
wx.hideLoading() //隐藏loading
if (res[0]) {
uni.showToast({
title: "数据获取失败",
icon: "none",
duration: 1500
})
resolve(false);
} else {
let data = res[1].data;
if (data.code == 1) {
resolve(data);
} else {
resolve(data);
}
}
}).catch(error => {
wx.hideLoading() //隐藏loading
reject(error);
})
})
return promise
}
2.再新建 api.js 进行请求地址封装
import { https } from './https.js'; // 引入刚刚封装好的https
class api {
//获取学费列表
async studentUserMsgsGetTuitionALL(params) {
const res = await https({
url: 'api/v1/getTuitionAll', //这里放你的请求路径
method: 'post',
data: params
})
return res
}
//获取合同列表
async bktstudentContract(params) {
const res = await https({
url: 'api/v1/index',
method: 'post',
data: params
})
return res
}
//查看收据
async studentUserGetReceipt(params) {
const res = await https({
url: 'api/v1/getReceipt',
method: 'post',
data: params
})
return res
}
}
export default new api()
3.在 main.js 中全局引入挂载
import api from './pages/api/api.js'
Vue.prototype.$api = api
4.页面直接使用
// 获取合同列表
bktstudentContract() {
this.$api.bktstudentContract().then((res) => {
if (res.code == 200) {
this.contractList = res.data;
} else {
uni.showToast({
title: res.data,
icon: "none",
position: 'top',
duration: 2000
});
}
});
},
//传参的这样写:
// 获取收据列表
studentUserGetReceipt() {
const params = {
student_msg_id: this.infoId,
};
this.$api.studentUserGetReceipt(params).then((res) => {
if (res.code == 200) {
this.receiptList = res.data;
} else {
uni.showToast({
title: res.data,
icon: "none",
position: 'top',
duration: 2000
});
}
});
},