一、新建api文件夹
在项目目录下创建api文件夹,内放files跟index.js文件夹,files文件夹内放每个页面对应的js请求接口
1、index.js
/**
* api接口的统一出口
*/
const api = {};
const requireComponent = require.context('./files', false, /\.js$/)
requireComponent.keys().forEach(fileName => {
const componentName = fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
const componentConfig = requireComponent(fileName)
api[componentName] = componentConfig.default
})
export default api;
2、例如:login.js
/**
* 登录用到的接口
*/
import http from '@/utils/http.js'
import config from '@/utils/config.js'
const login = {
//角色001-账号登录
transportLogin(data){
return new Promise((resolve, reject) => {
http.request({
domain:config.adminDomain,//接口ip地址+端口号(第一种)
url: "/user/login",
method: "POST",
data,
callBack: res => {
resolve(res);
}
})
})
},
//角色002-账号登录
regulatorLogin(data){
return new Promise((resolve, reject) => {
http.request({
domain:config.domain,//接口ip地址+端口号(第二种)
url: "/wx/login",
method: "POST",
data,
callBack: res => {
resolve(res);
}
})
})
}
}
export default login;
二、config.js
const domain = "http://192.888.888.6:80/my"
const adminDomain = "http://192.888.444.9:800"
const adminH5 = "http://192.888.666.7:82/#";
module.exports = {
domain,
adminDomain,
adminH5
}
三、main.js
四、页面使用
<template>
<view class="login-btn" @click="toLogin">登录</view>
<view class="login-btn" @click="toLogin2">登录</view>
</template>
methods: {
toLogin(){
this.$api.login.transportLogin(data).then(res=>{
uni.hideLoading()
if (res.code === 200) {
// 保存登陆信息
uni.setStorageSync('loginResult', res)
uni.setStorageSync('token', res.token);
uni.setStorageSync('login',false);
uni.reLaunch({
url: "/pages/learning/learning"
})
}
})
},
toLogin2(){
let data = {
account: "", //用户名
pwd: "" //密码
};
this.$api.login.regulatorLogin(data).then(res=>{
uni.hideLoading()
if (res.code === 200) {
// 保存登陆信息
uni.setStorageSync('loginResult', res)
uni.setStorageSync('token', res.token);
uni.setStorageSync('login',false);
uni.reLaunch({
url: "/pages/learning/learning"
})
}
})
}
}