Browse Source

feat: app.vue

refact
xuesinan 4 years ago
parent
commit
970cf9a364
  1. 169
      App.vue
  2. 1
      CHANGELOG.md
  3. 49
      apis/tall.js
  4. 12
      apis/wbs.js
  5. 8
      common/js/config.js
  6. 31
      main.js
  7. 3
      package.json
  8. 8
      pages/user/login.vue
  9. 2
      store/user/actions.js
  10. 45
      store/user/mutations.js
  11. 114
      utils/cache.js
  12. 324
      utils/cacheAndRequest.js
  13. 206
      utils/storage.js
  14. 61
      utils/tall.js
  15. 480
      utils/time.js
  16. 5
      utils/ui.js
  17. 226
      utils/upload.js

169
App.vue

@ -1,84 +1,99 @@
<script>
import { ref, computed } from 'vue';
import store from '@/store/index.js';
import ui from '@/utils/ui.js';
import storage from '@/utils/storage.js';
<script>
import { ref, computed } from 'vue';
import store from '@/store/index.js';
export default {
setup() {
return {
export default {
setup() {
return {
}
},
async onLaunch(options) {
console.log('options: ', options);
this.checkNetwork(); //
this.getSystemInfo(); //
// - H5APP
/* #ifndef MP-WEIXIN */
if (!store.state.user.token) {
// tokenuserIdtoken
// token userId
if (!options.query || !options.query.u) {
// u (userId)
ui.showToast('缺少用户信息参数');
} else {
const data = await store.dispatch('user/getTokenByUserId', options.query.u);
this.noPhone(data.phone);
}
}
/* #endif */
store.dispatch('socket/initSocket');
},
methods: {
// store
// 2g 3g ;
checkNetwork() {
uni.getNetworkType({
success: ({ networkType }) => {
store.commit('setNetworkConnected', !(networkType === 'none' || networkType === '2g' || networkType === '3g'));
},
});
//
uni.onNetworkStatusChange(({ isConnected, networkType }) => {
store.commit('setNetworkConnected', isConnected && !(networkType === '2g' || networkType === '3g'));
});
},
//
getSystemInfo() {
uni.getSystemInfo({
success: result => {
store.commit('setSystemInfo', result);
},
fail: error => {
console.error('getSystemInfo fail:', error);
},
});
},
/**
* 没有手机号 跳转绑定手机号的界面
* @param {string} phone
*/
async noPhone(phone) {
if (!phone) {
this.$u.route('/pages/phone-bind/phone-bind');
async onLaunch(options) {
console.log('options: ', options);
this.checkNetwork(); //
this.getSystemInfo(); //
// - H5APP
/* #ifndef MP-WEIXIN */
if (!store.state.user.token) {
// tokenuserIdtoken
// token userId
if (!options.query || !options.query.u) {
// u (userId)
this.$ui.showToast('缺少用户信息参数');
} else {
const data = await store.dispatch('user/getTokenByUserId', options.query.u);
this.noPhone(data.phone);
}
}
/* #endif */
store.dispatch('socket/initSocket');
},
methods: {
// store
// 2g 3g ;
checkNetwork() {
uni.getNetworkType({
success: ({ networkType }) => {
store.commit('setNetworkConnected', !(networkType === 'none' || networkType === '2g' || networkType === '3g'));
},
});
//
uni.onNetworkStatusChange(({ isConnected, networkType }) => {
store.commit('setNetworkConnected', isConnected && !(networkType === '2g' || networkType === '3g'));
});
},
//
getSystemInfo() {
uni.getSystemInfo({
success: result => {
store.commit('setSystemInfo', result);
},
fail: error => {
console.error('getSystemInfo fail:', error);
},
});
},
//
async signin() {
try {
const data = await uni.$u.api.signin();
if (data && data.token) {
store.commit('user/setUser', data);
store.commit('user/setToken', data.token);
this.noPhone(data.phone);
} else {
this.$ui.showToast('返回数据异常');
}
} catch (error) {
console.error('error: ', error);
this.$ui.showToast(error || '登录失败');
}
},
/**
* 没有手机号 跳转绑定手机号的界面
* @param {string} phone
*/
async noPhone(phone) {
if (!phone) {
this.$u.route('/pages/phone-bind/phone-bind');
}
},
}
}
}
</script>
<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/vk-uview-ui/index.scss";
@import '@/common/styles/iconfont.scss';
@import '@/common/styles/app.scss';
</script>
<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/vk-uview-ui/index.scss";
@import '@/common/styles/iconfont.scss';
@import '@/common/styles/app.scss';
</style>

1
CHANGELOG.md

@ -3,6 +3,7 @@
### 🌟 新功能
范围|描述|commitId
--|--|--
- | 使用uview完成api请求 | [1b3efd8](https://101.201.226.163:50022/TALL/TALL-MUI-4/commits/1b3efd8)
- | first commit | [8dc26de](https://101.201.226.163:50022/TALL/TALL-MUI-4/commits/8dc26de)
- | vue3 | [12ed2ad](https://101.201.226.163:50022/TALL/TALL-MUI-4/commits/12ed2ad)

49
apis/tall.js

@ -1,46 +1,45 @@
const apiUrl = 'https://test.tall.wiki/gateway'; // 测试
// const apiUrl = 'https://www.tall.wiki/gateway'; // 生产
import Config from '@/common/js/config.js'
const apiUrl = Config.apiUrl;
const tall = `${apiUrl}/tall3/v3.0`;
// 登录
// export const login = {
// async index(params) {
// try {
// const data = await uni.$u.http.post(`${tall}/users/signin`, params);
// return data;
// } catch (error) {
// throw new Error(error);
// }
// },
// };
export const login = {
async index(params) {
try {
const data = await uni.$u.http.post(`${tall}/users/signin`, params);
return data;
} catch (error) {
throw new Error(error);
}
},
};
export function setupTall(app) {
uni.$u.api = { ...uni.$u.api } || {};
// 登录
// app.config.globalProperties.$u.api.signin = params => login.index(params);
uni.$u.api.signin = params => login.index(params);
// 获取图片验证码
// app.config.globalProperties.$u.api.getImageCode = () => app.config.globalProperties.$u.get(`${tall}/users/code`);
uni.$u.api.getImageCode = () => uni.$u.get(`${tall}/users/code`);
// 获取短信验证码
// app.config.globalProperties.$u.api.getSmsCode = params => app.config.globalProperties.$u.get(`${tall}/users/smscode`, params);
uni.$u.api.getSmsCode = params => uni.$u.get(`${tall}/users/smscode`, params);
// 根据userId获取token
uni.$u.api.getToken = userId => uni.$u.get(`${tall}/users/userId`, { userId });
// 绑定手机号
// app.config.globalProperties.$u.api.phoneBind = (phone, smsCode) => app.config.globalProperties.$u.http.post(`${tall}/users/binding`, { phone, smsCode });
uni.$u.api.phoneBind = (phone, smsCode) => uni.$u.http.post(`${tall}/users/binding`, { phone, smsCode });
// 是否合并账号
// app.config.globalProperties.$u.api.phoneMerge = (phone, isMerge) => app.config.globalProperties.$u.http.post(`${tall}/users/merge`, { phone, isMerge });
uni.$u.api.phoneMerge = (phone, isMerge) => uni.$u.http.post(`${tall}/users/merge`, { phone, isMerge });
// 修改用户信息
// app.config.globalProperties.$u.api.updateUserInfo = params => app.config.globalProperties.$u.http.post(`${tall}/users/userInfo`, params);
uni.$u.api.updateUserInfo = params => uni.$u.http.post(`${tall}/users/userInfo`, params);
// 获取项目列表
// app.config.globalProperties.$u.api.getProjects = (startTime, endTime) => app.config.globalProperties.$u.post(`${tall}/project/query`, { startTime, endTime });
uni.$u.api.getProjects = (startTime, endTime) => uni.$u.post(`${tall}/project/query`, { startTime, endTime });
// 查询日历是否有小红点
// app.config.globalProperties.$u.api.findRedPoint = (startTime, endTime) => app.config.globalProperties.$u.post(`${tall}/project/day`, { startTime, endTime });
uni.$u.api.findRedPoint = (startTime, endTime) => uni.$u.post(`${tall}/project/day`, { startTime, endTime });
// 设置项目顺序
// app.config.globalProperties.$u.api.setProjectSort = params => app.config.globalProperties.$u.post(`${tall}/project/setProjectSort`, params);
uni.$u.api.setProjectSort = params => uni.$u.post(`${tall}/project/setProjectSort`, params);
// 设置项目父子结构
// app.config.globalProperties.$u.api.setProjectRelation = params => app.config.globalProperties.$u.post(`${tall}/project/setProjectRelation`, params);
uni.$u.api.setProjectRelation = params => uni.$u.post(`${tall}/project/setProjectRelation`, params);
// 删除某个项目
// app.config.globalProperties.$u.api.delProject = projectId => app.config.globalProperties.$u.post(`${tall}/project/deleteProject`, { projectId });
uni.$u.api.delProject = projectId => uni.$u.post(`${tall}/project/deleteProject`, { projectId });
}

12
apis/wbs.js

@ -1,7 +1,7 @@
const install = (Vue, vm) => {
vm.$u.api = { ...vm.$u.api } || {};
// 导入wbs
vm.$u.api.import = formData => vm.$t.chooseAndUpload(`${uni.$t.domain}/wbs`, formData);
};
import Config from "@/common/js/config.js"
export default { install };
export function setupWbs(app) {
uni.$u.api = { ...uni.$u.api } || {};
// 导入wbs
uni.$u.api.import = formData => this.$upload.chooseAndUpload(`${Config.apiUrl}/wbs`, formData);
}

8
common/js/config.js

@ -1,7 +1,7 @@
var config = {
baseUrl: 'https://test.tall.wiki',
apiUrl: 'https://test.tall.wiki/gateway',
msgUrl: 'wss://test.tall.wiki/websocket/message/v4.0/ws';
msgUrl: 'wss://test.tall.wiki/websocket/message/v4.0/ws',
projectPath: 'https://test.tall.wiki/tall-project',
// baseUrl: 'https://www.tall.wiki',
@ -10,12 +10,6 @@ var config = {
// projectPath: 'https://www.tall.wiki/tall-project',
version: 'v4.0.0'
VUE_APP_BASE_URL=
VUE_APP_API_URL=
VUE_APP_MSG_URL=
VUE_APP_PROJECT_PATH=
};
export default config;

31
main.js

@ -2,25 +2,36 @@ import { createSSRApp } from 'vue';
import App from './App';
import uView from './uni_modules/vk-uview-ui'; // 引入 uView UI
import store from "./store";
// import tall from '@/apis/tall.js';
// import request from '@/utils/request.js';
// import uTall from '@/utils/tall.js';
import { setupHttp } from '@/utils/request.js'
import { setupTall } from '@/apis/tall.js'
import { setupHttp } from '@/utils/request.js';
import { setupTall } from '@/apis/tall.js';
import { setupWbs } from '@/apis/wbs.js'
import dayjs from 'dayjs';
import 'dayjs/locale/zh-cn';
import cache from '@/utils/cache.js';
import cacheAndRequest from '@/utils/cacheAndRequest.js';
import storage from '@/utils/storage.js';
import time from '@/utils/time.js';
import ui from '@/utils/ui.js';
import upload from '@/utils/upload.js';
export function createApp() {
const app = createSSRApp(App)
app.use(uView); // 使用 uView UI
app.use(store);
// app.use(request);
// app.use(tall);
// app.use(uTall);
setupHttp(app);
setupTall(app);
setupWbs(app);
dayjs.locale('zh-cn');
// app.config.globalProperties.$tall = tall;
// app.config.globalProperties.$request = request;
app.config.globalProperties.$cache = cache;
app.config.globalProperties.$catchReq = cacheAndRequest;
app.config.globalProperties.$storage = storage;
app.config.globalProperties.$time = time;
app.config.globalProperties.$ui = ui;
app.config.globalProperties.$upload = upload;
return {
app

3
package.json

@ -4,7 +4,8 @@
"description": "",
"main": "main.js",
"dependencies": {
"axios": "^0.24.0"
"axios": "^0.24.0",
"dayjs": "^1.10.7"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.8.1",

8
pages/user/login.vue

@ -0,0 +1,8 @@
<template>
</template>
<script>
</script>
<style>
</style>

2
store/user/actions.js

@ -1,4 +1,3 @@
// import { getToken } from '@/apis/tall.js';
import ui from '@/utils/ui.js';
const actions = {
@ -14,7 +13,6 @@ const actions = {
commit('setUser', res);
return res;
} catch (error) {
console.log('222', error);
ui.showToast(error.msg || '获取个人信息失败');
}
},

45
store/user/mutations.js

@ -1,29 +1,28 @@
import storage from '@/utils/storage.js';
const mutations = {
/**
* 设置存储token
* @param {object} state
* @param {string} token
*/
setToken(state, token) {
state.token = token || '';
storage.setStorageSync('anyringToken', token || '');
// uni.$t.storage.setStorageSync('anyringToken', token || '');
// sessionStorage.setItem('token', user.token);
// sessionStorage.setItem('user', JSON.stringify(user));
},
/**
* 设置存储token
* @param {object} state
* @param {string} token
*/
setToken(state, token) {
state.token = token || '';
storage.setStorageSync('anyringToken', token || '');
},
/**
* 设置user数据
* @param {object} state
* @param {object} user
*/
setUser(state, user) {
if (!user) return;
state.user = { ...user };
storage.setStorageSync('user', JSON.stringify(user));
},
/**
* 设置user数据
* @param {object} state
* @param {object} user
*/
setUser(state, user) {
if (!user) return;
state.user = {
...user
};
storage.setStorageSync('user', JSON.stringify(user));
},
};
export default mutations;
export default mutations;

114
utils/cache.js

@ -1,62 +1,62 @@
export const filter = {
/**
* 过滤获取到的数据 根据开始截止时间
* @param {object} data 缓存拿到的数据
* @param {number} start ms
* @param {number} end ms
* @returns
*/
projects(data, start, end) {
if (!data || !data.length) return [];
return data.filter(item => start <= +item.endTime && end >= +item.startTime);
},
/**
* 过滤获取到的数据 根据开始截止时间
* @param {object} data 缓存拿到的数据
* @param {number} start ms
* @param {number} end ms
* @returns
*/
projects(data, start, end) {
if (!data || !data.length) return [];
return data.filter(item => start <= +item.endTime && end >= +item.startTime);
},
};
export default {
/**
* 项目列表某天的 获取
* @param {number} startTime
* @param {number} endTime
* @returns
*/
async getProjectsByDay(startTime, endTime) {
try {
const data = await uni.$t.storage.getStorage('projects');
return filter.projects(JSON.parse(data), startTime, endTime);
} catch (error) {
return [];
}
},
/**
* 项目列表某天的 获取
* @param {number} startTime
* @param {number} endTime
* @returns
*/
async getProjectsByDay(startTime, endTime) {
try {
const data = await uni.$t.storage.getStorage('projects');
return filter.projects(JSON.parse(data), startTime, endTime);
} catch (error) {
return [];
}
},
/**
* 项目列表
* @param {array} data
*/
putProjects(data) {
try {
if (!data || !data.length) return; // 服务端没数据不做操作
let value = uni.$t.storage.getStorageSync('projects');
let locals = value ? JSON.parse(value) : [];
if (!locals || !locals.length) {
// 本地没数据
locals = data || [];
} else {
// 本地有数据
data.forEach(item => {
let localData = locals.find(local => item.id === local.id);
if (localData) {
// 有相同数据 就用新的data里的数据
localData = item;
} else {
// 没有就直接存本地
locals.push(item);
}
});
}
uni.$t.storage.setStorage('projects', locals);
} catch (error) {
console.error('error: ', error);
uni.$t.storage.setStorage('projects', []);
}
},
};
/**
* 项目列表
* @param {array} data
*/
putProjects(data) {
try {
if (!data || !data.length) return; // 服务端没数据不做操作
let value = uni.$t.storage.getStorageSync('projects');
let locals = value ? JSON.parse(value) : [];
if (!locals || !locals.length) {
// 本地没数据
locals = data || [];
} else {
// 本地有数据
data.forEach(item => {
let localData = locals.find(local => item.id === local.id);
if (localData) {
// 有相同数据 就用新的data里的数据
localData = item;
} else {
// 没有就直接存本地
locals.push(item);
}
});
}
uni.$t.storage.setStorage('projects', locals);
} catch (error) {
console.error('error: ', error);
uni.$t.storage.setStorage('projects', []);
}
},
};

324
utils/cacheAndRequest.js

@ -6,185 +6,173 @@ import store from '@/store/index';
* @param {function} requestFn 执行请求的函数
*/
export const waitTokenRequest = requestFn => {
if (!requestFn || typeof requestFn !== 'function') throw new Error(`requestFn must be a function`);
if (uni.$t.storage.getStorageSync(uni.$t.app.tokenKey)) {
requestFn();
} else {
setTimeout(() => waitTokenRequest(requestFn), 10);
}
if (!requestFn || typeof requestFn !== 'function') throw new Error(`requestFn must be a function`);
if (uni.$t.storage.getStorageSync(uni.$t.app.tokenKey)) {
requestFn();
} else {
setTimeout(() => waitTokenRequest(requestFn), 10);
}
};
export default {
/**
* 获取项目列表
* @param {number} startTime 起始时间
* @param {number} endTime 截止时间
*/
getProjects(startTime, endTime, fn) {
let remote = false;
if (store.getters.useStorage) {
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache
.getProjectsByDay(startTime, endTime)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
}
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api
.getProjects(startTime, endTime)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putProjects(data);
})
.catch(err => fn(err));
});
},
/**
* 获取项目列表
* @param {number} startTime 起始时间
* @param {number} endTime 截止时间
*/
getProjects(startTime, endTime, fn) {
let remote = false;
if (store.getters.useStorage) {
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache.getProjectsByDay(startTime, endTime)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
}
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api.getProjects(startTime, endTime)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putProjects(data);
})
.catch(err => fn(err));
});
},
/**
* 通过项目id获取角色信息
* @param {object} params 提交的参数
*/
findShowRole(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache
.getShowRole(params.projectId)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
/**
* 通过项目id获取角色信息
* @param {object} params 提交的参数
*/
findShowRole(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache.getShowRole(params.projectId)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api
.findShowRole(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putShowRole(params.projectId, data);
})
.catch(err => fn(err));
});
},
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api.findShowRole(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putShowRole(params.projectId, data);
})
.catch(err => fn(err));
});
},
/**
* 根据时间基准点和角色查找定期任务
* @param {object} params 提交的参数
*/
getRegularTask(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache
.getStorageRegularTask(params)
.then(data => {
console.log('cache data: ', data);
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
/**
* 根据时间基准点和角色查找定期任务
* @param {object} params 提交的参数
*/
getRegularTask(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache.getStorageRegularTask(params)
.then(data => {
console.log('cache data: ', data);
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api
.getRegularTask(params)
.then(data => {
console.log('api data: ', uni.$u.deepClone(data));
remote = true;
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api.getRegularTask(params)
.then(data => {
console.log('api data: ', uni.$u.deepClone(data));
remote = true;
fn(null, uni.$u.deepClone(data));
// 存api到cache里
uni.$t.cache.putStorageRegularTask(params, data);
})
.catch(err => fn(err));
});
},
fn(null, uni.$u.deepClone(data));
// 存api到cache里
uni.$t.cache.putStorageRegularTask(params, data);
})
.catch(err => fn(err));
});
},
/**
* 根据角色查找永久的日常任务
* @param {object} params 提交的参数
*/
getPermanent(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache
.getStoragePermanent(params)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
/**
* 根据角色查找永久的日常任务
* @param {object} params 提交的参数
*/
getPermanent(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache.getStoragePermanent(params)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api
.getPermanent(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putStoragePermanent(params, data);
})
.catch(err => fn(err));
});
},
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api.getPermanent(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putStoragePermanent(params, data);
})
.catch(err => fn(err));
});
},
/**
* 根据时间和角色查找日常任务
* @param {object} params 提交的参数
*/
getGlobal(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache
.getDailyTask(params)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
/**
* 根据时间和角色查找日常任务
* @param {object} params 提交的参数
*/
getGlobal(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache.getDailyTask(params)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api
.getGlobal(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putDailyTask(params, data);
})
.catch(err => fn(err));
});
},
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api.getGlobal(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putDailyTask(params, data);
})
.catch(err => fn(err));
});
},
/**
* 获取插件信息
* @param {object} params 提交的参数
*/
getOtherPlugin(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache
.getPlugin(params.pluginId)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
/**
* 获取插件信息
* @param {object} params 提交的参数
*/
getOtherPlugin(params, fn) {
let remote = false;
// 有缓存 且 服务端数据未返回 就先返回缓存
uni.$t.cache.getPlugin(params.pluginId)
.then(data => {
!remote && fn(null, data);
})
.catch(err => !remote && fn(err));
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api
.getOtherPlugin(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putPlugin(params.pluginId, data);
})
.catch(err => fn(err));
});
},
};
waitTokenRequest(() => {
// 拿到api数据后 再用api的数据
uni.$u.api.getOtherPlugin(params)
.then(data => {
remote = true;
fn(null, data);
// 存api到cache里
uni.$t.cache.putPlugin(params.pluginId, data);
})
.catch(err => fn(err));
});
},
};

206
utils/storage.js

@ -1,112 +1,112 @@
export default {
/**
* 设置本地存储 同步
* @param {string} key
* @param {*} data
*/
setStorageSync(key, data) {
const value = typeof data === 'string' ? data : JSON.stringify(data);
uni.setStorageSync(key, value);
},
/**
* 设置本地存储 同步
* @param {string} key
* @param {*} data
*/
setStorageSync(key, data) {
const value = typeof data === 'string' ? data : JSON.stringify(data);
uni.setStorageSync(key, value);
},
/**
* 获取本地存储的信息 根据key
* @param {string} key
* @return {string}
*/
getStorageSync(key) {
return uni.getStorageSync(key);
},
/**
* 获取本地存储的信息 根据key
* @param {string} key
* @return {string}
*/
getStorageSync(key) {
return uni.getStorageSync(key);
},
/**
* 根据key移除某条数据 同步
* @param {string} key
*/
removeStorageSync(key) {
uni.removeStorageSync(key);
},
/**
* 根据key移除某条数据 同步
* @param {string} key
*/
removeStorageSync(key) {
uni.removeStorageSync(key);
},
/**
* 清楚全部数据 同步
*/
clearStorageSync() {
uni.clearStorageSync();
},
/**
* 清楚全部数据 同步
*/
clearStorageSync() {
uni.clearStorageSync();
},
/**
* 设置本地存储 异步
* @param {string} key
* @param {*} data
*/
setStorage(key, data) {
uni.$t.storage.checkCapacity();
return new Promise((resolve, reject) => {
const value = typeof data === 'string' ? data : JSON.stringify(data);
uni.setStorage({
key,
data: value,
success() {
resolve(`数据${key}存储成功`);
},
fail() {
reject(`数据${key}存储失败`);
},
});
});
},
/**
* 设置本地存储 异步
* @param {string} key
* @param {*} data
*/
setStorage(key, data) {
uni.$t.storage.checkCapacity();
return new Promise((resolve, reject) => {
const value = typeof data === 'string' ? data : JSON.stringify(data);
uni.setStorage({
key,
data: value,
success() {
resolve(`数据${key}存储成功`);
},
fail() {
reject(`数据${key}存储失败`);
},
});
});
},
/**
* 获取本地存储的信息 根据key 异步
* @param {string} key
* @return {string}
*/
getStorage(key) {
return new Promise((resolve, reject) => {
uni.getStorage({
key,
success(res) {
resolve(res.data);
},
fail(error) {
reject(`数据${key}获取失败, error: ${error.errMsg}`);
},
});
});
},
/**
* 获取本地存储的信息 根据key 异步
* @param {string} key
* @return {string}
*/
getStorage(key) {
return new Promise((resolve, reject) => {
uni.getStorage({
key,
success(res) {
resolve(res.data);
},
fail(error) {
reject(`数据${key}获取失败, error: ${error.errMsg}`);
},
});
});
},
/**
* 根据key移除某条数据 异步
* @param {string} key
*/
removeStorage(key) {
return new Promise((resolve, reject) => {
uni.removeStorage({
key,
success(res) {
resolve(res);
},
fail(error) {
reject(`数据${key}删除失败, error: ${error}`);
},
});
});
},
/**
* 根据key移除某条数据 异步
* @param {string} key
*/
removeStorage(key) {
return new Promise((resolve, reject) => {
uni.removeStorage({
key,
success(res) {
resolve(res);
},
fail(error) {
reject(`数据${key}删除失败, error: ${error}`);
},
});
});
},
/**
* 清楚全部数据 异步
*/
clearStorage() {
uni.clearStorage();
},
/**
* 清楚全部数据 异步
*/
clearStorage() {
uni.clearStorage();
},
// 检测local Storage容量 超出容量清空数据缓存
checkCapacity() {
/* #ifdef H5 */
const capacity = JSON.stringify(localStorage).length;
let max = 1024 * 1024 * 4;
if (capacity >= max) {
uni.$t.storage.clearStorage();
}
/* #endif */
},
};
// 检测local Storage容量 超出容量清空数据缓存
checkCapacity() {
/* #ifdef H5 */
const capacity = JSON.stringify(localStorage).length;
let max = 1024 * 1024 * 4;
if (capacity >= max) {
uni.$t.storage.clearStorage();
}
/* #endif */
},
};

61
utils/tall.js

@ -1,35 +1,36 @@
import app from '@/config/app.js';
import cache from '@/utils/cache.js';
import cacheAndRequest from '@/utils/cacheAndRequest.js';
import storage from '@/utils/storage.js';
import time from '@/utils/time.js';
import ui from '@/utils/ui.js';
import upload from '@/utils/upload.js';
import user from '@/config/user.js';
import zIndex from '@/config/zIndex.js';
// import app from '@/config/app.js';
// import cache from '@/utils/cache.js';
// import cacheAndRequest from '@/utils/cacheAndRequest.js';
// import storage from '@/utils/storage.js';
// import time from '@/utils/time.js';
// import ui from '@/utils/ui.js';
// import upload from '@/utils/upload.js';
// import user from '@/config/user.js';
// import zIndex from '@/config/zIndex.js';
const gateway = process.env.VUE_APP_API_URL;
// const gateway = process.env.VUE_APP_API_URL;
const $t = {
zIndex, // 定位元素层级
app, // app级别的相关配置
storage, // 本地存储storage封装
time, // 时间处理
ui, // ui界面提示相关
chooseAndUpload: upload.chooseAndUpload, // 选择并上传单个文件相关的封装
domain: `${gateway}/defaultwbs`,
cache, // 本地存储相关
$q: cacheAndRequest,
user, // 用户相关配置
};
// const $t = {
// zIndex, // 定位元素层级
// app, // app级别的相关配置
// storage, // 本地存储storage封装
// time, // 时间处理
// ui, // ui界面提示相关
// chooseAndUpload: upload.chooseAndUpload, // 选择并上传单个文件相关的封装
// domain: `${gateway}/defaultwbs`,
// cache, // 本地存储相关
// $q: cacheAndRequest,
// user, // 用户相关配置
// };
uni.$t = $t;
// uni.$t = $t;
const install = Vue => {
// Vue.prototype.$t = $t;
Vue.config.globalProperties.$t = $t;
};
// const install = Vue => {
// // Vue.prototype.$t = $t;
// Vue.config.globalProperties.$t = $t;
// };
export default {
install
};
// export default {
// install
// };

480
utils/time.js

@ -1,20 +1,20 @@
import dayjs from 'dayjs';
const advancedFormat = require('dayjs/plugin/advancedFormat');
const weekOfYear = require('dayjs/plugin/weekOfYear');
const duration = require('dayjs/plugin/duration');
// const advancedFormat = require('dayjs/plugin/advancedFormat');
// const weekOfYear = require('dayjs/plugin/weekOfYear');
// const duration = require('dayjs/plugin/duration');
dayjs.extend(advancedFormat);
dayjs.extend(weekOfYear);
dayjs.extend(duration);
// dayjs.extend(advancedFormat);
// dayjs.extend(weekOfYear);
// dayjs.extend(duration);
/**
* 格式化数字
* @param {*} n
*/
const formatNumber = n => {
const str = n.toString();
return str[1] ? str : `0${str}`;
const str = n.toString();
return str[1] ? str : `0${str}`;
};
/**
@ -22,15 +22,15 @@ const formatNumber = n => {
* @param {number} beginTime
*/
const formatTime = beginTime => {
const date = new Date(beginTime);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const date = new Date(beginTime);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
return `${[year, month, day].map(formatNumber).join('/')} ${[hour, minute, second].map(formatNumber).join(':')}`;
};
/**
@ -40,8 +40,8 @@ const formatTime = beginTime => {
* @param {string} cycle
*/
const add = (time, num, cycle) => {
const str = dayjs(time).add(num, cycle);
return str;
const str = dayjs(time).add(num, cycle);
return str;
};
/**
@ -50,11 +50,11 @@ const add = (time, num, cycle) => {
* @returns {{hours: number, minutes: number}}
*/
const convertTime = time => {
const arr = time.split(':');
return {
hours: parseInt(arr[0], 10),
minutes: parseInt(arr[1], 10),
};
const arr = time.split(':');
return {
hours: parseInt(arr[0], 10),
minutes: parseInt(arr[1], 10),
};
};
/**
@ -62,12 +62,12 @@ const convertTime = time => {
* @param {number} seconds
*/
const secondToMinute = seconds => {
const minute = formatNumber(Math.floor(seconds / 60));
const second = formatNumber(parseInt(seconds % 60, 10));
return {
minute,
second,
};
const minute = formatNumber(Math.floor(seconds / 60));
const second = formatNumber(parseInt(seconds % 60, 10));
return {
minute,
second,
};
};
/**
@ -76,18 +76,18 @@ const secondToMinute = seconds => {
* @return date:2018/10/09 time: 12:59
*/
const setTimestampToStr = timestamp => {
const timeObj = new Date(timestamp);
const year = timeObj.getFullYear();
const month = formatNumber(timeObj.getMonth() + 1);
const day = formatNumber(timeObj.getDate());
const hour = formatNumber(timeObj.getHours());
const minute = formatNumber(timeObj.getMinutes());
const date = `${year}-${month}-${day}`;
const time = `${hour}:${minute}`;
return {
date,
time,
};
const timeObj = new Date(timestamp);
const year = timeObj.getFullYear();
const month = formatNumber(timeObj.getMonth() + 1);
const day = formatNumber(timeObj.getDate());
const hour = formatNumber(timeObj.getHours());
const minute = formatNumber(timeObj.getMinutes());
const date = `${year}-${month}-${day}`;
const time = `${hour}:${minute}`;
return {
date,
time,
};
};
/**
@ -95,9 +95,10 @@ const setTimestampToStr = timestamp => {
* @param {Number} time 时间戳
*/
const validateTimeIsToday = time => {
const timeDate = new Date(time);
const date = new Date();
return timeDate.getFullYear() === date.getFullYear() && timeDate.getMonth() === date.getMonth() && timeDate.getDate() === date.getDate();
const timeDate = new Date(time);
const date = new Date();
return timeDate.getFullYear() === date.getFullYear() && timeDate.getMonth() === date.getMonth() && timeDate
.getDate() === date.getDate();
};
/**
@ -107,8 +108,8 @@ const validateTimeIsToday = time => {
* @param {string} cycle 传入 day 将会比较 day month和 year
*/
const isSame = (time, value, cycle) => {
const str = dayjs(time).isSame(value, cycle);
return str;
const str = dayjs(time).isSame(value, cycle);
return str;
};
/**
@ -120,25 +121,25 @@ const isSame = (time, value, cycle) => {
* 否则 ** :
*/
const formatBeginTime = timestamp => {
const timeObj = new Date(timestamp);
const year = timeObj.getFullYear();
const month = formatNumber(timeObj.getMonth() + 1);
const day = formatNumber(timeObj.getDate());
const hour = formatNumber(timeObj.getHours());
const minute = formatNumber(timeObj.getMinutes());
const date = `${year}/${month}/${day}`;
const time = `${hour}:${minute}`;
const currentYear = new Date().getFullYear();
const timeObj = new Date(timestamp);
const year = timeObj.getFullYear();
const month = formatNumber(timeObj.getMonth() + 1);
const day = formatNumber(timeObj.getDate());
const hour = formatNumber(timeObj.getHours());
const minute = formatNumber(timeObj.getMinutes());
const date = `${year}/${month}/${day}`;
const time = `${hour}:${minute}`;
const currentYear = new Date().getFullYear();
if (validateTimeIsToday(timestamp)) {
// 今天
return `今天 ${time}`;
} else if (currentYear !== year) {
// 不是今年
return `${date} ${time}`;
} else {
return `${month}${day}${time}`;
}
if (validateTimeIsToday(timestamp)) {
// 今天
return `今天 ${time}`;
} else if (currentYear !== year) {
// 不是今年
return `${date} ${time}`;
} else {
return `${month}${day}${time}`;
}
};
/**
@ -150,42 +151,42 @@ const formatBeginTime = timestamp => {
* 超过2小时 2 * 60 * 60 * 1000 ms 转换成小时 + 分钟数
*/
const formatDuration = duration => {
const minuteTime = 60 * 1000;
const hourTime = 60 * minuteTime;
const dayTime = 24 * hourTime;
const days = Math.floor(duration / dayTime);
const hours = Math.floor((duration % dayTime) / hourTime);
const minutes = Math.floor((duration % hourTime) / minuteTime);
if (duration <= 60 * 1000) {
// 小于1分钟 返回几秒
return `${Math.floor(duration / 1000)}`;
} else if (duration > dayTime) {
// 大于1天
if (minutes === 0) {
if (hours === 0) {
// 分钟数是0 和 小时数是0 返回 几天
return `${days}`;
} else {
// 分钟是0 小时不是0 返回 几天几小时
return `${days}${hours}小时`;
}
} else {
// 分钟不是0 返回几天几时几分
return `${days}${hours}${minutes}`;
}
} else if (duration > 2 * hourTime) {
// 大于2h
if (minutes === 0) {
// 分钟是0 返回几小时
return `${hours}小时`;
} else {
// 分钟不是0 返回几小时几分钟
return `${hours}小时${minutes}分钟`;
}
} else {
// 其余情况 返回 几分钟
return `${parseInt(duration / minuteTime)}分钟`;
}
const minuteTime = 60 * 1000;
const hourTime = 60 * minuteTime;
const dayTime = 24 * hourTime;
const days = Math.floor(duration / dayTime);
const hours = Math.floor((duration % dayTime) / hourTime);
const minutes = Math.floor((duration % hourTime) / minuteTime);
if (duration <= 60 * 1000) {
// 小于1分钟 返回几秒
return `${Math.floor(duration / 1000)}`;
} else if (duration > dayTime) {
// 大于1天
if (minutes === 0) {
if (hours === 0) {
// 分钟数是0 和 小时数是0 返回 几天
return `${days}`;
} else {
// 分钟是0 小时不是0 返回 几天几小时
return `${days}${hours}小时`;
}
} else {
// 分钟不是0 返回几天几时几分
return `${days}${hours}${minutes}`;
}
} else if (duration > 2 * hourTime) {
// 大于2h
if (minutes === 0) {
// 分钟是0 返回几小时
return `${hours}小时`;
} else {
// 分钟不是0 返回几小时几分钟
return `${hours}小时${minutes}分钟`;
}
} else {
// 其余情况 返回 几分钟
return `${parseInt(duration / minuteTime)}分钟`;
}
};
/**
@ -197,53 +198,53 @@ const formatDuration = duration => {
* 超过2小时 2 * 60 * 60 * 1000 ms 转换成{ days: 0, hours, minutes, seconds: 0 }
*/
const formatDurationToObject = duration => {
const minuteTime = 60 * 1000;
const hourTime = 60 * minuteTime;
const dayTime = 24 * hourTime;
const days = Math.floor(duration / dayTime);
const hours = Math.floor((duration % dayTime) / hourTime);
const minutes = Math.floor((duration % hourTime) / minuteTime);
const result = {
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
};
if (duration <= 60 * 1000) {
// 小于1分钟 返回几秒
result.seconds = Math.floor(duration / 1000);
} else if (duration > dayTime) {
// 大于1天
if (minutes === 0) {
if (hours === 0) {
// 分钟数是0 和 小时数是0 返回 几天
result.days = days;
} else {
// 分钟是0 小时不是0 返回 几天几小时
result.days = days;
result.hours = hours;
}
} else {
// 分钟不是0 返回几天几时几分
result.days = days;
result.hours = hours;
result.minutes = minutes;
}
} else if (duration > 2 * hourTime) {
// 大于2h
if (minutes === 0) {
// 分钟是0 返回几小时
result.hours = hours;
} else {
// 分钟不是0 返回几小时几分钟
result.hours = hours;
result.minutes = minutes;
}
} else {
// 其余情况 返回 几分钟
result.minutes = minutes;
}
return result;
const minuteTime = 60 * 1000;
const hourTime = 60 * minuteTime;
const dayTime = 24 * hourTime;
const days = Math.floor(duration / dayTime);
const hours = Math.floor((duration % dayTime) / hourTime);
const minutes = Math.floor((duration % hourTime) / minuteTime);
const result = {
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
};
if (duration <= 60 * 1000) {
// 小于1分钟 返回几秒
result.seconds = Math.floor(duration / 1000);
} else if (duration > dayTime) {
// 大于1天
if (minutes === 0) {
if (hours === 0) {
// 分钟数是0 和 小时数是0 返回 几天
result.days = days;
} else {
// 分钟是0 小时不是0 返回 几天几小时
result.days = days;
result.hours = hours;
}
} else {
// 分钟不是0 返回几天几时几分
result.days = days;
result.hours = hours;
result.minutes = minutes;
}
} else if (duration > 2 * hourTime) {
// 大于2h
if (minutes === 0) {
// 分钟是0 返回几小时
result.hours = hours;
} else {
// 分钟不是0 返回几小时几分钟
result.hours = hours;
result.minutes = minutes;
}
} else {
// 其余情况 返回 几分钟
result.minutes = minutes;
}
return result;
};
/**
@ -252,7 +253,7 @@ const formatDurationToObject = duration => {
* @return 时长的ms
*/
const formatObjectTimeToMs = (days = 0, hours = 0, minutes = 0, seconds = 0) => {
return days * 24 * 60 * 60 * 1000 + hours * 60 * 60 * 1000 + minutes * 60 * 1000 + seconds * 1000;
return days * 24 * 60 * 60 * 1000 + hours * 60 * 60 * 1000 + minutes * 60 * 1000 + seconds * 1000;
};
/**
@ -261,23 +262,23 @@ const formatObjectTimeToMs = (days = 0, hours = 0, minutes = 0, seconds = 0) =>
* @return {string} cycle 周期英文字符串
*/
const computeCycle = time => {
// 加载下一个周期的任务
let cycle = 'day';
switch (time) {
case '天':
cycle = 'day';
break;
case '周':
cycle = 'week';
break;
case '月':
cycle = 'month';
break;
default:
cycle = '日程';
break;
}
return cycle;
// 加载下一个周期的任务
let cycle = 'day';
switch (time) {
case '天':
cycle = 'day';
break;
case '周':
cycle = 'week';
break;
case '月':
cycle = 'month';
break;
default:
cycle = '日程';
break;
}
return cycle;
};
/**
@ -286,26 +287,26 @@ const computeCycle = time => {
* @param {number|string} time 时间
*/
const formatStartTimeToCycleTime = (cycle, time) => {
let result = '';
const _time = dayjs(+time);
switch (cycle) {
case '天':
result = _time.format('YYYY年M月D日');
break;
case '周':
result = _time.format('YYYY年w周');
break;
case '月':
result = _time.format('YYYY年M月');
break;
case '日程':
result = _time.format('YYYY年M月D日 HH:mm');
break;
default:
result = _time.format('YYYY年M月D日');
break;
}
return result;
let result = '';
const _time = dayjs(+time);
switch (cycle) {
case '天':
result = _time.format('YYYY年M月D日');
break;
case '周':
result = _time.format('YYYY年w周');
break;
case '月':
result = _time.format('YYYY年M月');
break;
case '日程':
result = _time.format('YYYY年M月D日 HH:mm');
break;
default:
result = _time.format('YYYY年M月D日');
break;
}
return result;
};
/**
@ -314,53 +315,70 @@ const formatStartTimeToCycleTime = (cycle, time) => {
* @returns { num: 显示的数字, time: 演示器演示时长 }
*/
const computeDurationText = leftTime => {
try {
if (leftTime < 0) return { num: 0, time: null };
const { years, months, days, hours, minutes, seconds, milliseconds } = dayjs.duration(leftTime).$d;
let num = 0;
let time = 1000;
try {
if (leftTime < 0) return {
num: 0,
time: null
};
const {
years,
months,
days,
hours,
minutes,
seconds,
milliseconds
} = dayjs.duration(leftTime).$d;
let num = 0;
let time = 1000;
if (years > 0) {
num = years;
time = 60 * 60 * 1000; // 按小时
} else if (months > 0) {
num = months;
time = 60 * 60 * 1000; // 按小时
} else if (days > 0) {
num = days;
time = 60 * 60 * 1000; // 按小时
} else if (hours > 0) {
num = hours;
} else if (minutes > 0) {
num = minutes;
} else if (seconds > 0) {
num = seconds;
} else if (milliseconds > 0) {
num = milliseconds;
time = 16;
} else {
time = null;
}
return { num, time };
} catch (error) {
console.log('🚀 ~ file: time.js ~ line 335 ~ computeDurationText ~ error', error);
return { num: 0, time: null };
}
if (years > 0) {
num = years;
time = 60 * 60 * 1000; // 按小时
} else if (months > 0) {
num = months;
time = 60 * 60 * 1000; // 按小时
} else if (days > 0) {
num = days;
time = 60 * 60 * 1000; // 按小时
} else if (hours > 0) {
num = hours;
} else if (minutes > 0) {
num = minutes;
} else if (seconds > 0) {
num = seconds;
} else if (milliseconds > 0) {
num = milliseconds;
time = 16;
} else {
time = null;
}
return {
num,
time
};
} catch (error) {
console.log('🚀 ~ file: time.js ~ line 335 ~ computeDurationText ~ error', error);
return {
num: 0,
time: null
};
}
};
export default {
formatNumber,
formatTime,
add,
convertTime,
secondToMinute,
setTimestampToStr,
isSame,
formatBeginTime,
formatDuration,
formatDurationToObject,
formatObjectTimeToMs,
computeCycle,
formatStartTimeToCycleTime,
computeDurationText,
};
formatNumber,
formatTime,
add,
convertTime,
secondToMinute,
setTimestampToStr,
isSame,
formatBeginTime,
formatDuration,
formatDurationToObject,
formatObjectTimeToMs,
computeCycle,
formatStartTimeToCycleTime,
computeDurationText,
};

5
utils/ui.js

@ -46,10 +46,7 @@ export default {
title,
content,
showCancel,
success: ({
confirm,
cancel
}) => {
success: ({ confirm, cancel }) => {
confirm && resolve();
cancel && reject();
},

226
utils/upload.js

@ -1,110 +1,118 @@
// H5选择文件
const chooseFileH5 = (extension = ['.xls', '.xlsx']) => {
return new Promise((resolve, reject) => {
uni.chooseFile({
count: 1, //默认100
extension,
success(res) {
resolve(res.tempFilePaths[0]);
},
fail() {
reject('上传失败');
},
});
});
};
// 微信选择文件 从客户端会话选择文件。
const chooseFileWeixin = (extension = ['.xls', '.xlsx']) => {
return new Promise((resolve, reject) => {
wx.chooseMessageFile({
count: 1,
extension,
type: 'file',
success(res) {
resolve(res.tempFiles[0].path);
},
fail() {
reject('上传失败');
},
});
});
};
// 选择文件
const chooseFile = (extension = ['.xls', '.xlsx']) => {
let fn = null;
/* #ifdef H5 */
fn = chooseFileH5(extension);
/* #endif */
/* #ifdef MP-WEIXIN */
fn = chooseFileWeixin(extension);
/* #endif */
return fn;
};
export default {
/**
* 上传单个文件
* @param {string} url 服务器地址
* @param {object} formData 上传的其他字段
* @param {array} extension 上传文件类型 扩展名数组
* @param {string} name
* @returns
*/
chooseAndUpload(url, formData = {}, extension = ['.xls', '.xlsx'], name = 'param') {
uni.hideLoading();
clearTimeout(timer);
let timer = null;
return new Promise((resolve, reject) => {
const token = uni.$t.storage.getStorageSync(uni.$t.app.tokenKey);
if (!token) {
return reject('用户未登录,请登录后重试');
}
chooseFile(extension)
.then(filePath => {
console.log('filePath: ', filePath);
if (!timer) {
timer = setTimeout(() => {
uni.$t.ui.showLoading('正在上传...');
timer = null;
}, 800);
}
// 开始上传
uni.uploadFile({
url,
filePath,
name,
formData,
header: { Authorization: `Bearer ${token}` },
success: ({ data, statusCode }) => {
clearTimeout(timer);
uni.hideLoading();
if (statusCode === 200 && data) {
const { code, msg } = JSON.parse(data);
if (code !== 200) {
reject(msg);
} else {
resolve(JSON.parse(data).data);
}
} else {
reject('上传失败');
}
},
fail: error => {
clearTimeout(timer);
uni.hideLoading();
reject(error);
},
});
})
.catch(error => {
clearTimeout(timer);
uni.hideLoading();
reject(error);
});
});
},
// H5选择文件
const chooseFileH5 = (extension = ['.xls', '.xlsx']) => {
return new Promise((resolve, reject) => {
uni.chooseFile({
count: 1, //默认100
extension,
success(res) {
resolve(res.tempFilePaths[0]);
},
fail() {
reject('上传失败');
},
});
});
};
// 微信选择文件 从客户端会话选择文件。
const chooseFileWeixin = (extension = ['.xls', '.xlsx']) => {
return new Promise((resolve, reject) => {
wx.chooseMessageFile({
count: 1,
extension,
type: 'file',
success(res) {
resolve(res.tempFiles[0].path);
},
fail() {
reject('上传失败');
},
});
});
};
// 选择文件
const chooseFile = (extension = ['.xls', '.xlsx']) => {
let fn = null;
/* #ifdef H5 */
fn = chooseFileH5(extension);
/* #endif */
/* #ifdef MP-WEIXIN */
fn = chooseFileWeixin(extension);
/* #endif */
return fn;
};
export default {
/**
* 上传单个文件
* @param {string} url 服务器地址
* @param {object} formData 上传的其他字段
* @param {array} extension 上传文件类型 扩展名数组
* @param {string} name
* @returns
*/
chooseAndUpload(url, formData = {}, extension = ['.xls', '.xlsx'], name = 'param') {
uni.hideLoading();
clearTimeout(timer);
let timer = null;
return new Promise((resolve, reject) => {
const token = uni.$t.storage.getStorageSync(uni.$t.app.tokenKey);
if (!token) {
return reject('用户未登录,请登录后重试');
}
chooseFile(extension)
.then(filePath => {
console.log('filePath: ', filePath);
if (!timer) {
timer = setTimeout(() => {
uni.$t.ui.showLoading('正在上传...');
timer = null;
}, 800);
}
// 开始上传
uni.uploadFile({
url,
filePath,
name,
formData,
header: {
Authorization: `Bearer ${token}`
},
success: ({
data,
statusCode
}) => {
clearTimeout(timer);
uni.hideLoading();
if (statusCode === 200 && data) {
const {
code,
msg
} = JSON.parse(data);
if (code !== 200) {
reject(msg);
} else {
resolve(JSON.parse(data).data);
}
} else {
reject('上传失败');
}
},
fail: error => {
clearTimeout(timer);
uni.hideLoading();
reject(error);
},
});
})
.catch(error => {
clearTimeout(timer);
uni.hideLoading();
reject(error);
});
});
},
};

Loading…
Cancel
Save