1.env.js
// 统一管理所有地址
const devUrl = 'http://192.17.000.000:000';
const proUrl = 'http://192.17.000.000:000';
const prefix1 = '/api/XXX';
const prefix2 = '/api/XXXX';
const config = {
// 开发环境配置
development: {
rootUrl: devUrl,
imgUrl: devUrl + '/images/',
gateway1: prefix1,
gateway2: prefix2,
},
// 生产环境配置
production: {
rootUrl: proUrl,
imgUrl: proUrl + '/images/',
gateway1: prefix1,
gateway2: prefix2,
}
}
export default config[process.env.NODE_ENV];
2.interceptor.js
import config from '@/env.js';
const install = (Vue, vm) => {
// 这个配置是一次配置,全局通用的,具体参数见 https://www.uviewui.com/js/http.html
Vue.prototype.$u.http.setConfig({
baseUrl: config.rootUrl, // 请求的本域名
header: {
Host: config.rootUrl?.slice(8)
},
showLoading: true, // 是否显示请求中的loading
loadingText: '正在加载...', // 请求loading中的文字提示
loadingTime: 800, // 在此时间内,请求还没回来的话,就显示加载中动画,单位ms
originalData: true // 是否在拦截器中返回服务端的原始数据
});
// 请求拦截部分,如配置,每次请求前都会执行
Vue.prototype.$u.http.interceptor.request = (config) => {
const token = vm.vuex_token;
if (token) {
config.header = {
'Authorization': token && `Bearer ${token}`
}
}
// 不缓存get请求
if (config.method === 'get') {
config.header['Cache-Control'] = 'no-cache'
}
return config;
}
// 响应拦截,如配置,每次请求结束都会执行本方法
Vue.prototype.$u.http.interceptor.response = (res) => {
if (res.statusCode == 200) {
let result = res.data;
if (!result.success) {
vm.$u.toast(result.msg);
if (result.status === '402') {
setTimeout(() => {
vm.$u.route({
url: '/pages/account/firstPage',
type: 'reLaunch'
})
}, 1000)
}
}
return result;
} else if (res.statusCode == 401) {
vm.$u.route({
url: '/pages/account/firstPage',
type: 'reLaunch'
})
} else if (res.statusCode == 422) {
vm.$u.toast(res.error)
} else if (res.statusCode == 500) {
vm.$u.toast(res.data?.msg)
} else {
vm.$u.route({
url: '/pages/account/error',
type: 'reLaunch'
})
}
}
}
export default {
install
}
http.js
import * as user from './modules/user.js';
const install = (Vue, vm) => {
Vue.prototype.$api = {
// test get api
getSearch: (params = {}) => vm.$u.get('/http/search', params),
// test get loading
getReqLoading: (params = {}) => vm.$u.get('/http/reqloading', params),
// modules import
user,
};
}
export default {
install
}
user.js
import Vue from 'vue';
let vm = new Vue();
// test get api
export function getUserInfo(params) {
return vm.$u.get('/Info', params)
}
// test post api
export function GetNoticeList(params) {
return vm.$u.post(`/List`, params)
}
commons/tools.js (常用公共方法
import config from '@/env.js'
import {
GetDataItemDetail
} from '../apis/modules/user.js'
const install = (Vue, vm) => {
Vue.prototype.$t = {
bg(name) {
return {
background: `url(${config.rootUrl}/GetImg/${name}) no-repeat`,
backgroundSize: '100% 100%'
}
},
// 背景图片 静态资源
bgAssets(name) {
return {
background: `url(${config.imgUrl}${name}) no-repeat`,
backgroundSize: '100% 100%'
}
},
// 服务器地址拼接图片缩略图
imgs(name) {
return `${config.rootUrl}/images/GetImg/${name}_s?timestamp=${new Date().getTime()}`
},
img(name) {
return `${config.rootUrl}/images/GetImg/${name}?timestamp=${new Date().getTime()}`
},
/**
* 千位分割
* @param { number }
*/
formatPrice(amount) {
if (amount) {
amount = (+amount).toFixed(2);
var re = /\d{1,3}(?=(\d{3})+$)/g;
var n1 = amount.replace(/^(\d+)((\.\d+)?)$/, function(s, s1, s2) {
return s1.replace(re, "$&,") + s2;
});
return n1;
} else {
return 0;
}
},
uploadImg() {
return `${config.rootUrl}/images/UploadImg`
},
uploadVedio() {
return `${config.rootUrl}/video/UploadVideo`
},
//数据字典
DataItem(ItemCode) {
let arr = []
return GetDataItemDetail({
ItemCode
}).then(res => {
arr = res.response.map((item) => {
return {
label: item.ItemName,
value: item.ItemValue
}
})
return arr
})
},
showLabel(type, list) {
if (type !== '') {
let tag = list.find(item =>
item.value == type
)
return tag ? tag.label : ''
}
},
}
}
export default {
install
}
store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let lifeData = {};
try {
// 尝试获取本地是否存在lifeData变量,第一次启动APP时是不存在的
lifeData = uni.getStorageSync('lifeData');
} catch (e) {
console.log(e)
}
// 需要永久存储,且下次APP启动需要取出的,在state中的变量名
let saveStateKeys = ['vuex_token','vuex_phone', 'vuex_userId',
'vuex_userName',
];
// 保存变量到本地存储中
const saveLifeData = function(key, value) {
// 判断变量名是否在需要存储的数组中
if (saveStateKeys.indexOf(key) != -1) {
// 获取本地存储的lifeData对象,将变量添加到对象中
let tmp = uni.getStorageSync('lifeData');
// 第一次打开APP,不存在lifeData变量,故放一个{}空对象
tmp = tmp ? tmp : {};
tmp[key] = value;
// 执行这一步后,所有需要存储的变量,都挂载在本地的lifeData对象中
uni.setStorageSync('lifeData', tmp);
}
}
const {
vuex_token,
vuex_phone,
vuex_userId,
vuex_userName,
} = lifeData;
const store = new Vuex.Store({
// 下面这些值仅为示例,使用过程中请删除
state: {
// 如果上面从本地获取的lifeData对象下有对应的属性,就赋值给state中对应的变量
// 加上vuex_前缀,是防止变量名冲突,也让人一目了然
vuex_token,
vuex_phone, // 用户手机号
vuex_userId, // 用户id
vuex_userName,
},
mutations: {
$uStore(state, payload) {
// 判断是否多层级调用,state中为对象存在的情况,诸如user.info.score = 1
let nameArr = payload.name.split('.');
let saveKey = '';
let len = nameArr.length;
if (nameArr.length >= 2) {
let obj = state[nameArr[0]];
for (let i = 1; i < len - 1; i++) {
obj = obj[nameArr[i]];
}
obj[nameArr[len - 1]] = payload.value;
saveKey = nameArr[0];
} else {
// 单层级变量,在state就是一个普通变量的情况
state[payload.name] = payload.value;
saveKey = payload.name;
}
// 保存变量到本地,见顶部函数定义
saveLifeData(saveKey, state[saveKey])
}
}
})
export default store
store/mixin.js
// $u.mixin.js
import {
mapState
} from 'vuex'
import store from "@/store"
// 尝试将用户在根目录中的store/index.js的vuex的state变量,全部加载到全局变量中
let $uStoreKey = [];
try {
$uStoreKey = store.state ? Object.keys(store.state) : [];
} catch (e) {
}
module.exports = {
created() {
// 将vuex方法挂在到$u中
// 使用方法为:如果要修改vuex的state中的user.name变量为"史诗" => this.$u.vuex('user.name', '史诗')
// 如果要修改vuex的state的version变量为1.0.1 => this.$u.vuex('version', '1.0.1')
this.$u.vuex = (name, value) => {
this.$store.commit('$uStore', {
name,
value
})
}
},
computed: {
// 将vuex的state中的所有变量,解构到全局混入的mixin中
...mapState($uStoreKey)
}
}
main.js
import Vue from 'vue'
import App from './App'
import store from '@/store'
Vue.config.productionTip = false
App.mpType = 'app'
// 引入全局uView
import uView from 'uview-ui'
Vue.use(uView);
// 全局引入vuex
let vuexStore = require("@/store/$u.mixin.js");
Vue.mixin(vuexStore)
const app = new Vue({
...App,
store
})
// http拦截器,将此部分放在new Vue()和app.$mount()之间,才能App.vue中正常使用
import httpInterceptor from '@/apis/interceptor.js'
Vue.use(httpInterceptor, app)
// http接口API集中管理引入部分
import httpApi from '@/apis/http.js'
Vue.use(httpApi, app)
import tools from '@/commons/tools.js';
Vue.use(tools, app)
app.$mount();