order.js
var util = require('../../../utils/util.js');
var api = require('../../../config/api.js');
Page({
data: {
orderList: [],
showType: 0,
page: 1,
size: 10,
totalPages: 1
},
onLoad: function(options) {
// 页面初始化 options为页面跳转所带来的参数
let that = this
try {
var tab = wx.getStorageSync('tab');
this.setData({
showType: tab
});
} catch (e) {}
},
getOrderList() {
let that = this;
util.request(api.OrderList, {
showType: that.data.showType,
page: that.data.page,
size: that.data.size
}).then(function(res) {
if (res.errno === 0) {
console.log(res.data);
that.setData({
orderList: that.data.orderList.concat(res.data.data),
totalPages: res.data.totalPages
});
}
});
},
onReachBottom() {
if (this.data.totalPages > this.data.page) {
this.setData({
page: this.data.page + 1
});
this.getOrderList();
} else {
wx.showToast({
title: '没有更多订单了',
icon: 'none',
duration: 2000
});
return false;
}
},
switchTab: function(event) {
let showType = event.currentTarget.dataset.index;
this.setData({
orderList: [],
showType: showType,
page: 1,
size: 10,
totalPages: 1
});
this.getOrderList();
},
// “去付款”按钮点击效果
payOrder: function (e) {
let that = this;
let orderId = e.currentTarget.dataset.index;
util.request(api.OrderPrepay, {
orderId: orderId
}, 'POST').then(function (res) {
if (res.errno === 0) {
const payParam = res.data;
console.log("支付过程开始");
wx.requestPayment({
'timeStamp': payParam.timeStamp,
'nonceStr': payParam.nonceStr,
'package': payParam.packageValue,
'signType': payParam.signType,
'paySign': payParam.paySign,
'success': function (res) {
console.log("支付过程成功");
util.redirect('/pages/ucenter/order/order');
},
'fail': function (res) {
console.log("支付过程失败");
util.showErrorToast('支付失败');
},
'complete': function (res) {
console.log("支付过程结束")
}
});
}
});
},
// “取消订单”点击效果
cancelOrder: function (e) {
let that = this;
let orderId = e.currentTarget.dataset.index;
wx.showModal({
title: '',
content: '确定要取消此订单?',
success: function (res) {
if (res.confirm) {
util.request(api.OrderCancel, {
orderId: orderId
}, 'POST').then(function (res) {
if (res.errno === 0) {
wx.showToast({
title: '取消订单成功'
});
util.redirect('/pages/ucenter/order/order');
} else {
util.showErrorToast(res.errmsg);
}
});
}
}
});
},
// “取消订单并退款”点击效果
refundOrder: function (e) {
let that = this;
let orderId = e.currentTarget.dataset.index;
wx.showModal({
title: '',
content: '确定要取消此订单?',
success: function (res) {
if (res.confirm) {
util.request(api.OrderRefund, {
orderId: orderId
}, 'POST').then(function (res) {
if (res.errno === 0) {
wx.showToast({
title: '取消订单成功'
});
util.redirect('/pages/ucenter/order/order');
} else {
util.showErrorToast(res.errmsg);
}
});
}
}
});
},
// “删除”点击效果
deleteOrder: function (e) {
let that = this;
let orderId = e.currentTarget.dataset.index;
wx.showModal({
title: '',
content: '确定要删除此订单?',
success: function (res) {
if (res.confirm) {
util.request(api.OrderDelete, {
orderId: orderId
}, 'POST').then(function (res) {
if (res.errno === 0) {
wx.showToast({
title: '删除订单成功'
});
util.redirect('/pages/ucenter/order/order');
} else {
util.showErrorToast(res.errmsg);
}
});
}
}
});
},
// “确认收货”点击效果
confirmOrder: function (e) {
let that = this;
let orderId = e.currentTarget.dataset.index;
wx.showModal({
title: '',
content: '确认收货?',
success: function (res) {
if (res.confirm) {
util.request(api.OrderConfirm, {
orderId: orderId
}, 'POST').then(function (res) {
if (res.errno === 0) {
wx.showToast({
title: '确认收货成功!'
});
util.redirect('/pages/ucenter/order/order');
} else {
util.showErrorToast(res.errmsg);
}
});
}
}
});
},
detailExpress:function(e){
let orderId = e.currentTarget.dataset.index;
wx.navigateTo({url:'/pages/ucenter/expressInfo/expressInfo?orderId=' + orderId});
},
onReady: function() {
// 页面渲染完成
},
onShow: function() {
this.setData({
orderList: [],
page: 1,
size: 10,
totalPages: 1
});
this.getOrderList();
},
onHide: function() {
// 页面隐藏
},
onUnload: function() {
// 页面关闭
}
})
order.wxml
<view class="container">
<view class="orders-switch">
<view class="item {{ showType == 0 ? 'active' : ''}}" bindtap="switchTab" data-index='0'>
<view class="txt">全部</view>
</view>
<view class="item {{ showType == 1 ? 'active' : ''}}" bindtap="switchTab" data-index='1'>
<view class="txt">待付款</view>
</view>
<view class="item {{ showType == 2 ? 'active' : ''}}" bindtap="switchTab" data-index='2'>
<view class="txt">待发货</view>
</view>
<view class="item {{ showType == 3 ? 'active' : ''}}" bindtap="switchTab" data-index='3'>
<view class="txt">待收货</view>
</view>
<view class="item {{ showType == 4 ? 'active' : ''}}" bindtap="switchTab" data-index='4'>
<view class="txt">待评价</view>
</view>
</view>
<view class="no-order" wx:if="{{orderList.length <= 0}}">
<view class="c">
<image src="/static/images/noCart.png" />
</view>
</view>
<view class="orders">
<view class="order" wx:for="{{orderList}}" wx:key="id">
<navigator url="../orderDetail/orderDetail?id={{item.id}}" class="h">
<view class="l">订单编号:{{item.orderSn}}</view>
<view class="r">{{item.orderStatusText}}</view>
</navigator>
<navigator url="../orderDetail/orderDetail?id={{item.id}}" class="goods">
<view class="item" wx:for="{{item.goodsList}}" wx:key="id" wx:for-item="gitem">
<view class="img">
<image src="{{gitem.picUrl}}"></image>
</view>
<view class="info">
<view class="t">
<text class="name">{{gitem.goodsName}}</text>
</view>
<view class="t">
<text class="attr">{{gitem.specifications}}</text>
<text class="number">共 {{gitem.number}} 件商品</text>
</view>
<view class="price">¥{{gitem.price}}</view>
<view class="btn active" wx:if="{{item.handleOption.comment && (gitem.comment == 0)}}">
<navigator url="../../commentPost/commentPost?orderId={{gitem.orderId}}&&valueId={{gitem.goodsId}}&type=0">去评价</navigator>
</view>
<view class="btn active" wx:if="{{item.handleOption.rebuy}}">
<navigator url="../../goods/goods?id={{gitem.goodsId}}">再次购买</navigator>
</view>
</view>
</view>
</navigator>
<view class="b">
<view class="l">实付:
<text class="cost">¥{{item.actualPrice}}</text>
</view>
<view class="r">
<view class="btn active" data-index="{{item.id}}" bindtap="cancelOrder" wx:if="{{item.handleOption.cancel}}">取消订单</view>
<view class="btn active" data-index="{{item.id}}" bindtap="payOrder" wx:if="{{item.handleOption.pay}}">去付款</view>
<view class="btn active" data-index="{{item.id}}" bindtap="detailExpress" wx:if="{{item.handleOption.confirm}}">查看物流</view>
<view class="btn active" data-index="{{item.id}}" bindtap="confirmOrder" wx:if="{{item.handleOption.confirm}}">确认收货</view>
<view class="btn active" data-index="{{item.id}}" bindtap="deleteOrder" wx:if="{{item.handleOption.delete}}">删除订单</view>
<view class="btn active" data-index="{{item.id}}" bindtap="refundOrder" wx:if="{{item.handleOption.refund}}">申请退款</view>
</view>
</view>
</view>
</view>
</view>
utils.js
var api = require('../config/api.js');
var app = getApp();
function formatTime(date) {
var year = date.getFullYear()
var month = date.getMonth() + 1
var day = date.getDate()
var hour = date.getHours()
var minute = date.getMinutes()
var second = date.getSeconds()
return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
function formatNumber(n) {
n = n.toString()
return n[1] ? n : '0' + n
}
/**
* 封封微信的的request
*/
function request(url, data = {}, method = "GET") {
return new Promise(function(resolve, reject) {
wx.request({
url: url,
data: data,
method: method,
header: {
'Content-Type': 'application/json',
'X-Dts-Token': wx.getStorageSync('token')
},
success: function(res) {
if (res.statusCode == 200) {
if (res.data.errno == 501) {
// 清除登录相关内容
try {
wx.removeStorageSync('userInfo');
wx.removeStorageSync('token');
} catch (e) {
// Do something when catch error
}
// 切换到登录页面
wx.navigateTo({
url: '/pages/auth/login/login'
});
} else {
resolve(res.data);
}
} else {
reject(res.errMsg);
}
},
fail: function(err) {
reject(err)
}
})
});
}
function redirect(url) {
//判断页面是否需要登录
if (false) {
wx.redirectTo({
url: '/pages/auth/login/login'
});
return false;
} else {
wx.redirectTo({
url: url
});
}
}
function showErrorToast(msg) {
wx.showToast({
title: msg,
image: '/static/images/icon_error.png'
})
}
function jhxLoadShow(message) {
if (wx.showLoading) { // 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
wx.showLoading({
title: message,
mask: true
});
} else { // 低版本采用Toast兼容处理并将时间设为20秒以免自动消失
wx.showToast({
title: message,
icon: 'loading',
mask: true,
duration: 20000
});
}
}
function jhxLoadHide() {
if (wx.hideLoading) { // 基础库 1.1.0 微信6.5.6版本开始支持,低版本需做兼容处理
wx.hideLoading();
} else {
wx.hideToast();
}
}
module.exports = {
formatTime,
request,
redirect,
showErrorToast,
jhxLoadShow,
jhxLoadHide
}
api.js
// 以下是业务服务器API地址
// 本机开发API地址
var WxApiRoot = 'http://localhost:8080/demo/wx/';
// 测试环境部署api地址
// var WxApiRoot = 'http://192.168.0.101:8070/demo/wx/';
// 线上云平台api地址
//var WxApiRoot = 'https://www.dtsshop.com/demo/wx/';
module.exports = {
IndexUrl: WxApiRoot + 'home/index', //首页数据接口
};
app.json
{
"pages": [
"pages/index/index",
"pages/about/about",
"pages/comments/comments",
"pages/detail/detail",
"pages/hot/hot",
"pages/logs/logs",
"pages/list/list",
"pages/page/page",
"pages/poster/poster",
"pages/readlog/readlog",
"pages/search/search",
"pages/topic/topic",
"pages/theme/theme",
"pages/webpage/webpage",
"pages/tags/tags",
"pages/my/my",
"pages/my/payment/index",
"pages/my/phone/index",
"pages/my/profile/index",
"pages/channels/channels"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTextStyle": "black",
"pageOrientation": "portrait",
"navigationStyle": "custom",
"navigationBarHideCloseButton": false,
"navigationBarHideMoreButton": false
},
"tabBar": {
"color": "#959595",
"selectedColor": "#118fff",
"borderStyle": "white",
"backgroundColor": "#ffffff",
"list": [
{
"pagePath": "pages/index/index",
"text": " "
},
{
"pagePath": "pages/topic/topic",
"text": " "
},
{
"pagePath": "pages/hot/hot",
"text": " "
},
{
"pagePath": "pages/my/my",
"text": " "
}
]
},
"usingComponents": {
"ui-sys": "mp-cu/colorUI/components/ui-sys/ui-sys",
"ui-title": "mp-cu/colorUI/components/ui-title/ui-title",
"ui-avatar": "mp-cu/colorUI/components/ui-avatar/ui-avatar",
"ui-search-bar": "/mp-cu/colorUI/components/ui-search-bar/ui-search-bar",
"ui-swiper": "/mp-cu/colorUI/components/ui-swiper/ui-swiper",
"ui-loading": "mp-cu/colorUI/components/ui-loading/ui-loading",
"ui-menu": "mp-cu/colorUI/components/ui-menu/ui-menu",
"ui-menu-item": "mp-cu/colorUI/components/ui-menu-item/ui-menu-item",
"ui-avatar-stack": "mp-cu/colorUI/components/ui-avatar-stack/ui-avatar-stack",
"ui-modal": "mp-cu/colorUI/components/ui-modal/ui-modal",
"ui-toast": "mp-cu/colorUI/components/ui-toast/ui-toast",
"ui-switch": "mp-cu/colorUI/components/ui-switch/ui-switch",
"ui-radio-group": "mp-cu/colorUI/components/ui-radio-group/ui-radio-group",
"ui-radio": "mp-cu/colorUI/components/ui-radio/ui-radio",
"ui-card": "mp-cu/colorUI/components/ui-card/ui-card",
"ui-fixed": "mp-cu/colorUI/components/ui-fixed/ui-fixed",
"ui-img": "mp-cu/colorUI/components/ui-img/ui-img",
"ui-navbar": "/mp-cu/colorUI/components/ui-navbar/ui-navbar",
"ui-text-size": "/mp-cu/colorUI/components/ui-text-size/ui-text-size",
"ui-tag": "/mp-cu/colorUI/components/ui-tag/ui-tag",
"ui-progress": "/mp-cu/colorUI/components/ui-progress/ui-progress",
"ui-tab": "/mp-cu/colorUI/components/ui-tab/ui-tab",
"ui-popover": "/mp-cu/colorUI/components/ui-popover/ui-popover",
"ui-steps": "/mp-cu/colorUI/components/ui-steps/ui-steps",
"ui-form": "/mp-cu/colorUI/components/ui-form/ui-form",
"ui-form-group": "/mp-cu/colorUI/components/ui-form-group/ui-form-group",
"ui-input-box": "/mp-cu/colorUI/components/ui-input-box/ui-input-box",
"ui-checkbox": "/mp-cu/colorUI/components/ui-checkbox/ui-checkbox",
"ui-checkbox-group": "/mp-cu/colorUI/components/ui-checkbox-group/ui-checkbox-group",
"ui-change-theme": "/mp-cu/colorUI/components/ui-change-theme/ui-change-theme",
"video-channels": "./components/video-channels/video-channels"
},
"requiredBackgroundModes": [
"audio",
"location"
],
"networkTimeout": {
"request": 10000,
"connectSocket": 10000,
"uploadFile": 10000,
"downloadFile": 10000
},
"sitemapLocation": "sitemap.json",
"resizable": false,
"darkmode": true
}
app.js
/*
*
* 微慕小程序开源版
*
*/
import { colorUI } from './utils/uiconfig'
App({
colorUI,
onLaunch: function () {
this.updateManager();
// wx.setEnableDebug({
// enableDebug: true
// })
},
/*小程序主动更新
*/
updateManager() {
if (!wx.canIUse('getUpdateManager')) {
return false;
}
const updateManager = wx.getUpdateManager();
updateManager.onCheckForUpdate(function (res) {
});
updateManager.onUpdateReady(function () {
wx.showModal({
title: '有新版本',
content: '新版本已经准备好,即将重启',
showCancel: false,
success(res) {
if (res.confirm) {
updateManager.applyUpdate()
}
}
});
});
updateManager.onUpdateFailed(function () {
wx.showModal({
title: '更新提示',
content: '新版本下载失败',
showCancel: false
})
});
},
globalData: {
userInfo: null,
openid: '',
isGetUserInfo: false,
isGetOpenid: false
}
})
uiconfig.js 使用
//框架核心配置
import ColorUI from '../mp-cu/main'
export const colorUI = new ColorUI({
config: {
theme: 'auto',
main: 'blue',
footer: false,
text: 1,
tabBar: [{
title: '首页',
icon: 'cicon-home-sm-o',
curIcon: 'cicon-home-line',
url: '/pages/index/index',
type: 'tab'
},
{
title: '分类',
icon: 'cicon-discover-o',
curIcon: 'cicon-discover',
url: '/pages/topic/topic',
type: 'tab'
},
{
title: '排行',
icon: 'cicon-upstage-o',
curIcon: 'cicon-upstage',
url: '/pages/hot/hot',
type: 'tab'
},
{
title: '我的',
icon: 'cicon-my-o',
curIcon: 'cicon-my',
url: '/pages/my/my',
type: 'tab'
}],
}
})
main.js定义
import { CUStoreInit } from '/store/index'
let version = '3.3.1';
let store = {}, sys_info = wx.getSystemInfoSync();
let baseMethod = {
//设置主题a
setTheme(data) {
store.setState({'sys_theme': data})
wx.setStorageSync('sys_theme', data);
//跟随系统
if (data === 'auto') {
setStatusStyle(wx.getSystemInfoSync().theme === 'light' ? 'dark' : 'light');
} else {
setStatusStyle(data === 'light' ? 'dark' : 'light');
}
},
//设置主颜色
setMain(data) {
store.setState({sys_main: data});
wx.setStorageSync('sys_main', data);
},
//设置字号等级
setText(data) {
store.setState({sys_text: data});
wx.setStorageSync('sys_text', data);
},
$showDialog({title , content , showCancel , cancelText, confirmText , success}) {
store.$p.map(item =>{
if(item.is.indexOf('components/ui-modal/ui-modal') > -1 ){
//强制更新所有页面的successBack 为设定的success
item['successBack'] = success
}
})
store.setState({
'$Modal.show': true,
'$dialog.title' : title,
'$dialog.content' : content,
'$dialog.showCancel' : showCancel,
'$dialog.cancelText' : cancelText,
'$dialog.confirmText' : confirmText
});
},
setToast( data) {
let key ={}
Object.assign(key,data);
console.log(key)
// state.toast = Object.assign(state.toast,data);
},
$tips(res, duration = 1500, mask = false, icon= '') {
if(_object(res)) {
store.setState({
'$toast.title': res.title || '',
'$toast.duration': res.duration || duration,
'$toast.icon': res.icon || icon,
'$toast.mask': res.mask || mask
})
} else {
store.setState({
'$toast.title': res,
'$toast.duration': duration,
'$toast.icon': icon,
'$toast.mask': mask,
})
}
},
$success(_,title='成功',duration=1500){
store.setState({
'$toast.title': title,
'$toast.duration': duration,
'$toast.icon': '_icon-check'
})
},
$error(_,title='错误',duration=1500){
store.setState({
'$toast.title' : title,
'$toast.duration' : duration,
'$toast.icon' : '_icon-warn',
})
},
$loading(title = '加载中' , duration = 1500){
store.setState({
'$toast.title' : title ,
'$toast.duration' : duration,
'$toast.icon' : '_icon-loading',
'$toast.isLoading':true
})
},
$hideLoading(){
store.setState({
'$toast.title' : '',
'$toast.icon' : '',
'$toast.isLoading':false
})
},
closeModal(){
store.setState({
'$Modal.show': false,
});
},
_toHome() {
wx.switchTab({
url: this.data.$cuStore.sys_home_page
});
},
_toPath(url, type = '') {
switch (type) {
case 'switchTab':
wx.switchTab({
url: url,
fail(res) {
console.log(res);
}
});
break;
case 'reLaunch':
wx.reLaunch({
url: url,
success(res) {
console.log(res);
},
fail(res) {
console.log(res);
}
});
break;
case 'redirectTo':
wx.redirectTo({
url: url,
fail(res) {
console.log(res);
}
});
break;
default:
wx.navigateTo({
url: url,
fail(res) {
console.log(res);
}
})
break;
}
},
_backPage() {
if (this.sys_isFirstPage()) {
this._toHome();
} else {
wx.navigateBack({
delta: 1
});
}
},
//实例是否为路由栈的第一个页面
sys_isFirstPage() {
return getCurrentPages().length === 1
},
}
//是否为对象
const _object = function (value) {
return Object.prototype.toString.call(value) === '[object Object]';
};
/**
* ColorUi 主Js文件
* config 下
* @param theme 设置默认主题
* @param main 设置默认强调色
* @param text 设置默认字号等级(0-4)
* @param footer 显示底部colorUI版权(如果属于开源作品,请带上ColorUI版权!!!)
* @param homePath 设置首页路径(一些组件会用到跳回主页,请每个项目设置好!)
* @param tabBar 配置系统tabBar
*/
export default class ColorUI {
constructor({config, data, state, methods}) {
//默认配置,防止没自定义配置时,出问题。
config.theme = config.theme||'auto'
config.main = config.main||'blue'
config.text = config.text||1
config.homePath = config.homePath||'/pages/index/index'
config.tabBar = config.tabBar||[]
config.shareTitle = config.shareTitle||''
//处理数据
this.config = config
this.data = data
this.methods = methods
this.state = state
this.$cuState = {};
this.colorUiInit()
}
//colorUi 主框架初始化
colorUiInit() {
//创建时,添加组件
const _create = function (r, o = {}) {
r.$cuStore = {};
const { useProp } = o;
if (o.hasOwnProperty("useProp")) {
if ((useProp && typeof useProp === "string") || Object.prototype.toString.call(useProp) === "[object Array]") {
r.$cuStore.useProp = [].concat(useProp);
} else {
r.$cuStore.useProp = [];
}
}
store.$p.push(r);
if (r.$cuStore.useProp) {
r.setData({
$cuStore: _filterKey(store.$cuStore, r.$cuStore.useProp, (key, useKey) => key === useKey),
});
} else {
r.setData({
$cuStore: store.state,
})
}
};
//销毁时,移除组件
const _destroy = function (r) {
let index = store.$p.findIndex((item) => item === r);
if (index > -1) {
store.$p.splice(index, 1);
}
};
store = CUStoreInit(this.config)
if (this.config.theme === 'auto') {
wx.onThemeChange((res) => {
store.setState({sys_theme: 'auto'})
wx.setStorageSync('sys_theme', 'auto');
setStatusStyle(wx.getSystemInfoSync().theme === 'light' ? 'dark' : 'light')
})
} else {
wx.setStorageSync('sys_theme', this.config.theme)
setStatusStyle(this.config.theme === 'light' ? 'dark' : 'light');
}
const originPage = Page
const originComponent = Component;
let that = this;
const _objData = function (o) {
return {
...(o.data || {}),
sys_info: sys_info,
sys_navBar: sys_info.statusBarHeight + 50,
sys_statusBar: sys_info.statusBarHeight,
sys_capsule: sys_capsule(),
version: version,
$cuData: that.data,
$cuConfig: that.config,
$cuStore: store.state
}
};
App.Page = function (o = {}, ...args) {
//将config 和 data 组装进data 里面
o.data = _objData(o);
//注入colorUi 函数体
Object.keys(baseMethod).forEach(key => {
if (typeof baseMethod[key] === 'function') {
o[key] = baseMethod[key]
}
})
o['setState'] = store.setState
//如果有配置methods,就注入设定的methods
if (that.methods) {
let pageLife = [
"data", "onLoad", "onShow", "onReady", "onHide", "onUnload", "onPullDownRefresh",
"onReachBottom", "onShareAppMessage", "onPageScroll", "onTabItemTap", "setTheme",
"setMain", "setText", "_toHome", "_toPath", "_backPage", "sys_isFirstPage"
]
Object.keys(that.methods).forEach((key) => {
if (typeof that.methods[key] === "function" && !pageLife.some((item) => item === key)) {
o[key] = that.methods[key];
}
});
}
const originCreate = o.onLoad;
o.onLoad = function () {
_create(this, o);
originCreate && originCreate.apply(this, arguments);
};
const originonDestroy = o.onUnload;
o.onUnload = function () {
_destroy(this);
originonDestroy && originonDestroy.apply(this, arguments);
};
//开启全局分享
if (that.config.share) {
//分享到朋友
//const onShareApp = o.onShareAppMessage;
o.onShareAppMessage = function () {
return {
title: that.config.shareTitle,
path: that.config.homePath
}
//_create(this, o);
//onShareApp && onShareApp.apply(this, arguments);
};
//分享到朋友圈
//const onShareTime = o.onShareTimeline;
o.onShareTimeline = function () {
return {
title: that.config.shareTitle,
query: that.config.homePath
}
//_create(this, o);
//onShareTime && onShareTime.apply(this, arguments);
};
}
originPage(o, ...args);
//console.log(o)
}
try {
Page = App.Page
} catch (e) { }
//重写组件
App.Component = function (o = {}, ...args) {
o.data = _objData(o);
o.methods || (o.methods = {})
o.methods['setState'] = store.setState
Object.keys(baseMethod).forEach(key => {
if (typeof baseMethod[key] === 'function') {
o.methods[key] = baseMethod[key]
}
})
const { lifetimes = {} } = o;
let originCreate = lifetimes.attached || o.attached, originonDestroy = lifetimes.detached || o.detached;
const attached = function () {
_create(this, o);
originCreate && originCreate.apply(this, arguments);
};
const detached = function () {
_destroy(this);
originonDestroy && originonDestroy.apply(this, arguments);
};
if (Object.prototype.toString.call(o.lifetimes) === "[object Object]") {
o.lifetimes.attached = attached;
o.lifetimes.detached = detached;
} else {
o.attached = attached;
o.detached = detached;
}
originComponent(o, ...args);
};
try {
Component = App.Component;
} catch (e) { }
console.log(
`%c colorUI 启动成功 %c 当前版本V` + version + `%c`,
'background:#0081ff; padding: 1px; border-radius: 3px 0 0 3px; color: #fff',
'background:#354855; padding: 1px 5px; border-radius: 0 3px 3px 0; color: #fff; font-weight: bold;',
'background:transparent'
)
}
}
//设置系统颜色 版本
export const setStatusStyle = (status) => {
if (status === 'light') {
wx.setNavigationBarColor({
frontColor: '#ffffff',
backgroundColor: '#000000',
animation: {
duration: 200,
timingFunc: 'easeIn'
}
});
} else {
wx.setNavigationBarColor({
frontColor: '#000000',
backgroundColor: '#ffffff',
animation: {
duration: 200,
timingFunc: 'easeIn'
}
});
}
}
//获取胶囊信息
export const sys_capsule = () => {
let capsule = wx.getMenuButtonBoundingClientRect();
if (!capsule) {
console.error('getMenuButtonBoundingClientRect error');
capsule = { bottom: 56, height: 32, left: 278, right: 365, top: 24, width: 87 };
}
return capsule;
}
store/index.js
import diff from '../lib/diff'
/**
* 数组或对象深拷贝
* @param data
* @returns {any}
*/
const nextArr = (data) => {
return JSON.parse(JSON.stringify(data));
};
/**
* 判断是否为数组
* @param value
* @returns {boolean}
*/
const ifArray = (value) => {
return value instanceof Array || Object.prototype.toString.call(value) === '[object Array]';
};
/**
* 判断是否为对象
* @param value
* @returns {boolean}
*/
const ifObject = (value) => {
return Object.prototype.toString.call(value) === '[object Object]';
};
const setData = (obj, data) => {
let result = nextArr(data), origin = nextArr(obj);
Object.keys(origin).forEach((key) => {
dataHandler(key, origin[key], result);
});
return result;
};
const dataHandler = (key, result, data) => {
let arr = pathHandler(key),d = data;
for (let i = 0; i < arr.length - 1; i++) {
keyToData(arr[i], arr[i + 1], d);
d = d[arr[i]];
}
d[arr[arr.length - 1]] = result;
};
const pathHandler = (key) => {
let current = "", keyArr = [];
for (let i = 0, len = key.length; i < len; i++) {
if (key[0] === "[") {
throw new Error("key值不能以[]开头");
}
if (key[i].match(/\.|\[/g)) {
cleanAndPush(current, keyArr);
current = "";
}
current += key[i];
}
cleanAndPush(current, keyArr);
return keyArr;
};
const cleanAndPush = (key, arr) => {
let r = cleanKey(key);
if (r !== "") {
arr.push(r);
}
};
const keyToData = (prev, current, data) => {
if (prev === "") {
return;
}
if (typeof current === "number" && !ifArray(data[prev])) {
data[prev] = [];
} else if (typeof current === "string" && !ifObject(data[prev])) {
data[prev] = {};
}
};
const cleanKey = (key) => {
if (key.match(/\[\S+\]/g)) {
let result = key.replace(/\[|\]/g, "");
if (!Number.isNaN(parseInt(result))) {
return +result;
} else {
throw new Error(`[]中必须为数字`);
}
}
return key.replace(/\[|\.|\]| /g, "");
};
export const CUStoreInit = (config) => {
let $store = {
state: {},
$p: [],
setState(obj, fn = () => { }) {
if (!ifObject(obj)) {
throw new Error("setState的第一个参数须为object!");
}
let prev = $store.state;
let current = setData(obj, prev);
$store.state = current;
//如果有组件
if ($store.$p.length > 0) {
let diffObj = diff(current, prev);
let keys = Object.keys(diffObj);
if (keys.length > 0) {
const newObj = {};
keys.forEach((key) => {
newObj["$cuStore." + key] = diffObj[key];
});
let pros = $store.$p.map((r) => {
if (r.$cuStore.hasOwnProperty("useProp")) {
let useProps = _filterKey(newObj, r.$cuStore.useProp,
(key, useKey) => key === "$cuStore." + useKey ||
!!key.match(new RegExp("^[$]cuStore." + useKey + "[.|[]", "g"))
);
if (Object.keys(useProps).length > 0) {
return new Promise((resolve) => {
r.setData(useProps, resolve);
});
} else {
return Promise.resolve();
}
}
return new Promise((resolve) => {
r.setData(newObj, resolve);
});
});
Promise.all(pros).then(fn);
} else {
fn();
}
} else {
fn();
}
}
}
$store.state.sys_theme = wx.getStorageSync('sys_theme') ? wx.getStorageSync('sys_theme') : config.theme
$store.state.sys_main = wx.getStorageSync('sys_main') ? wx.getStorageSync('sys_main') : config.main
$store.state.sys_text = wx.getStorageSync('sys_text') ? wx.getStorageSync('sys_text') : config.text
$store.state.sys_home_page = config.homePath
const modal = {
show: false,
dialog: {title:'', content:'', showCancel:true, cancelText:'取消', cancelColor:'', confirmText:'确定', confirmColor:'', success : ()=>{}},
toast: {title:'', icon:'', image:'', duration:1500, mask:false, isLoading:false, success:()=>{}},
}
$store.state.$Modal = modal
$store.state.$dialog = modal.dialog
$store.state.$toast = modal.toast
return $store
}
diff.js
/**
* diff库
* @update 2019.11.27
* @param {object} current - 当前状态
* @param {object} prev - 之前状态
*/
const diff = function diff(current = {}, prev = {}) {
let result = {};
updateDiff(current, prev, "", result);
nullDiff(current, prev, "", result);
return result;
};
/**
* 判断是否为数组
* @param value
* @returns {boolean}
*/
const ifArray = (value) => {
return value instanceof Array || Object.prototype.toString.call(value) === '[object Array]';
};
/**
* 判断是否为对象
* @param value
* @returns {boolean}
*/
const ifObject = (value) => {
return Object.prototype.toString.call(value) === '[object Object]';
};
const updateDiff = function updateDiff(current = {}, prev = {}, root = "", result = {}) {
if(ifArray(current) && ((ifArray(prev) && current.length !== prev.length) || !ifArray(prev))){
result[root] = current
return;
}
Object.entries(current).forEach(item => {
let key = item[0], value = item[1], path = root === "" ? key : root + "." + key;
if (ifArray(current)) {
path = root === "" ? key : root + "[" + key + "]";
}
if (!prev.hasOwnProperty(key)) {
result[path] = value;
} else if ((ifObject(prev[key]) && ifObject(current[key])) || (ifArray(prev[key]) && ifArray(current[key]))) {
updateDiff(current[key], prev[key], path, result);
} else if (prev[key] !== current[key]) {
result[path] = value;
}
});
return result;
};
const nullDiff = function nullDiff(current = {}, prev = {}, root = "", result = {}) {
if(ifArray(current) && ((ifArray(prev) && current.length !== prev.length) || !ifArray(prev))){
return;
}
Object.entries(prev).forEach(item => {
let key = item[0], path = root === "" ? key : root + "." + key;
if (ifArray(current)) {
path = root === "" ? key : root + "[" + key + "]";
}
if (!current.hasOwnProperty(key)) {
result[path] = null;
} else if ((ifObject(prev[key]) && ifObject(current[key])) || (ifArray(prev[key]) && ifArray(current[key]))) {
nullDiff(current[key], prev[key], path, result);
}
});
return result;
};
export default diff;