欢迎光临,了解微信小程序开发,就上易用通!

【工具】微信小程序常用工具类封装

发布:2018-01-25 09:19浏览: 来源:网络 作者:tianshu

做微信小程序当中,会遇到好多的工具类util.js,这里记载下来以便平常使用 
(Ps:建议通过目录查看)

-获取日期(格式化)
  1. function formatTime(date) {
  2.   var year = date.getFullYear()
  3.   var month = date.getMonth() + 1
  4.   var day = date.getDate()
  5.   var hour = date.getHours()
  6.   var minute = date.getMinutes()
  7.   var second = date.getSeconds()
  8.   return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
  9. }
  10. function formatNumber(n) {
  11.   n = n.toString()
  12.   return n[1] ? n : '0' + n
  13. }
  14. -获取动态更新时间
  15.  
  16. function getDateDiff (dateTimeStamp) {
  17.   var minute = 1000 * 60;
  18.   var hour = minute * 60;
  19.   var day = hour * 24;
  20.   var halfamonth = day * 15;
  21.   var month = day * 30;
  22.   var year = day * 365;
  23.   var now = new Date().getTime();
  24.   var diffValue = now - dateTimeStamp;
  25.   if(diffValue < 0){
  26.     //非法操作
  27.     return '数据出错';
  28.   }
  29.   var yearC = diffValue / year;
  30.   var monthC = diffValue / month;
  31.   var weekC = diffValue / (7 * day);
  32.   var dayC = diffValue / day;
  33.   var hourC = diffValue / hour;
  34.   var minC = diffValue / minute;
  35.   if(yearC >= 1){
  36.     result = parseInt(yearC) + '年以前';
  37.   }else if(monthC >= 1){
  38.     result = parseInt(monthC) + '个月前';
  39.   }else if(weekC >= 1){
  40.     result = parseInt(weekC) + '星期前';
  41.   }else if(dayC >= 1){
  42.     result = parseInt(dayC) + '天前';
  43.   }else if(hourC >= 1){
  44.     result = parseInt(hourC) + '小时前';
  45.   }else if(minC >= 5){
  46.     result = parseInt(minC) + '分钟前';
  47.   }else{
  48.     result = '刚刚发表';
  49.   }
  50.   return result;
  51. }
  52. import {Promise} from './promise.js';
  53. const noop = function() {};
  54. /**
  55. * 转换称两位数
  56. * 0 => 00
  57. */
  58. function formatNumber(n) {
  59.     n = n.toString();
  60.     return n[1] ? n : '0' + n;
  61. }
  62. /**
  63. * [秒 =》 分钟]
  64. * 100 => 01:40
  65. */
  66. function secondToMinute(s) {
  67.     let m = Math.floor(s / 60);
  68.     s = s % 60;
  69.     return [formatNumber(m), formatNumber(s)].join(":");
  70. }
  71. /**
  72. * 格式化时间
  73. */
  74. exports.formatTime = function(date, fmt = "yyyy/MM/dd hh:mm:ss") {
  75.     if (!date) return "";
  76.     date = typeof date == "number" ? new Date(date) : date;
  77.     var o = {
  78.         "M+": date.getMonth() + 1, //月份
  79.         "d+": date.getDate(), //日
  80.         "h+": date.getHours(), //小时
  81.         "m+": date.getMinutes(), //分
  82.         "s+": date.getSeconds(), //秒
  83.     };
  84.     if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  85.     for (var k in o) {
  86.         if (new RegExp("(" + k + ")").test(fmt)) {
  87.             fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ?
  88.                 (o[k]) :
  89.                 (("00" + o[k]).substr(("" + o[k]).length)));
  90.         }
  91.     }
  92.     return fmt;
  93. };
  94. /**
  95. * 人性话格式时间
  96. */
  97. exports.ctDate = function(date) {
  98.     if (!date) return "";
  99.     const now = Date.now();
  100.     let diff;
  101.     date = typeof date == "number" ? date : +(new Date(date));
  102.     diff = now - date;
  103.     switch (Math.floor(diff / 3600000 / 24)) {
  104.         case 0:
  105.             return "今天";
  106.         case 1:
  107.             return "昨天";
  108.         case 2:
  109.             return "两天前";
  110.         case 3:
  111.             return "三天前";
  112.         case 4:
  113.             return "四天前";
  114.         case 5:
  115.             return "五天前";
  116.         default:
  117.             return formatTime(date);
  118.     }
  119. };
  120. /**
  121. * 浅拷贝
  122. */
  123. const assign = exports.assign = function() {
  124.     const args = [].slice.apply(arguments);
  125.     const target = args.shift();
  126.     const length = args.length;
  127.     let i = 0;
  128.     let k;
  129.     for (; i < length; i++) {
  130.         let copy = args[i];
  131.         for (k in copy) {
  132.             target[k] = copy[k];
  133.         }
  134.     }
  135.     return target;
  136. };
  137. /**
  138. * 封装loadding
  139. */
  140. exports.loading = function(title = "加载中", duration = 10000, icon = "loading") {
  141.     wx.showToast({
  142.         title,
  143.         icon,
  144.         duration
  145.     });
  146. };
  147. /**
  148. * 封装hideLoading
  149. */
  150. exports.hideLoading = function() {
  151.     wx.hideToast();
  152. };
  153. /**
  154. * mode基类
  155. */
  156. function modal(options, showCancel = false) {
  157.     return new Promise((reslove, reject) => {
  158.         const SUCCESS = options.success || noop;
  159.         const FAIL = options.fail || noop;
  160.         options.success = function(res) {
  161.             SUCCESS(res);
  162.             if (res.confirm) {
  163.                 reslove(true);
  164.             } else {
  165.                 reslove(false);
  166.             }
  167.         };
  168.         options.fail = function(res) {
  169.             FAIL(res);
  170.             reject(res);
  171.         };
  172.         options.showCancel = showCancel;
  173.         wx.showModal(options);
  174.     });
  175. }
  176. /**
  177. * 判断model的
  178. * @param  {[type]} options [description]
  179. * @return {[type]}         [description]
  180. */
  181. function modalOptions (options) {
  182.   if (typeof options == "string") {
  183.       return {
  184.           title,
  185.           content: opt
  186.       };
  187.   }
  188.   return options;
  189. }
  190. /**
  191. * 弹出层
  192. */
  193. const _alert = exports._alert = function(options, title = "提示") {
  194.     options = modalOptions(options);
  195.     return model(options);
  196. };
  197. /**
  198. * 对话框
  199. */
  200. const _confirm = exports._confirm = function(options, title = "提示") {
  201.   options = modalOptions(options);
  202.   return modal(options,true);
  203. };
  204. exports.decodeHtml = function(domString) {
  205.     if (!domString) return "";
  206.     domString = typeof domString === "function" ? domString()  : domString.toString();
  207.     const REGX_HTML_DECODE = /&\w+;|&#(\d+);|<\w+>/g;
  208.     const HTML_DECODE = {
  209.         "&lt;": "<",
  210.         "&gt;": ">",
  211.         "&amp;": "&",
  212.         "&nbsp;": " ",
  213.         "&quot;": "\"",
  214.         "©": "",
  215.         "<br>": "\n",   //后端将\n转成了<br>
  216.     };
  217.     return domString.replace(REGX_HTML_DECODE,function(m,$1){
  218.       return HTML_DECODE[m] ? HTML_DECODE[m] : m;
  219.     });
  220. };
  221. //Object => queryString
  222. exports.param = function(obj) {
  223.     var key, val,
  224.         arr = [];
  225.     for (key in obj) {
  226.         val = obj[key];
  227.         arr[arr.length] = key + "=" + val;
  228.     }
  229.     return arr.join("&");
  230. };
  231. /**
  232. * 封装wx.request
  233. * 引入promise
  234. * 建议在app.js中引入request并且定义全局请求配置
  235. */
  236. function request(configuration) {
  237.     const DEFALUT_CONFIG = {
  238.         root: "",
  239.         url: "",
  240.         method: "POST",
  241.         header: {
  242.             "content-type": "application/x-www-form-urlencoded;charset=utf-8"
  243.         },
  244.         data: {},
  245.         success: noop,
  246.         fail: noop,
  247.         complete: noop,
  248.         resloveStatus: noop,
  249.         loading: false,
  250.     };
  251.     configuration = assign({},DEFALUT_CONFIG, configuration);
  252.     return function(requestParams) {
  253.         return new Promise(function(fulfill, reject) {
  254.                 requestParams = assign({},configuration, requestParams);
  255.                 if (requestParams.loading) {
  256.                     loading();
  257.                 }
  258.                 wx.request({
  259.                     /**
  260.                      * 每个项目的跟路径不一样,
  261.                      */
  262.                     url: requestParams.root + requestParams.url,
  263.                     method: requestParams.method,
  264.                     data: requestParams.data,
  265.                     header: requestParams.header,
  266.                     success({
  267.                         data
  268.                     }) {
  269.                         /**
  270.                          * 服务端通过code判断服务器超时/参数错误等
  271.                          */
  272.                         if (requestParams.resloveStatus(data)) {
  273.                             fulfill(data);
  274.                         } else {
  275.                             reject(data);
  276.                         }
  277.                     },
  278.                     fail(res) {
  279.                         /**
  280.                          * 可能是网络错误
  281.                          */
  282.                         reject(res);
  283.                     },
  284.                     complete() {
  285.                         requestParams.complete(res);
  286.                         hideLoading();
  287.                     }
  288.                 });
  289.             })
  290.             .then(function(res) {
  291.                 requestParams.success(res);
  292.                 return res;
  293.             }, function(res) {
  294.                 requestParams.fail(res);
  295.                 throw new Error("request fail:" + res);
  296.             });
  297.     };
  298. }
  299. /**
  300. * 配置获取用户信息的参数
  301. * @return {[type]}               [getUserInfo]
  302. */
  303. function configUserInfo(userInfo) {
  304.     const DETAULT_USERINFO = {
  305.         code: "",
  306.         data: {},
  307.         /**
  308.          * 把认证信息传到服务器登录
  309.          * @param  {[type]} userInfo [认证信息]
  310.          * @param  {[type]} code     [登录code]
  311.          * @return {[type]}          [promise]
  312.          */
  313.         requestLogin: function(userInfo, code) {
  314.             //必须返回一个promise
  315.             return {
  316.                 then: noop
  317.             };
  318.         }
  319.     };
  320.     userInfo = assign({},DETAULT_USERINFO, userInfo);
  321.     /**
  322.      * 获取自己的用户信息
  323.      * @param  {Function} callback [获取信息之后的回调]
  324.      * @param  {[type]}   force    [是否强制从服务器上使用新的code拉取用户信息]
  325.      * @return {[type]}            [promise]
  326.      */
  327.     return function getUserInfo(callback = noop, force = false) {
  328.         return new Promise(function(reslove, reject) {
  329.             if (userInfo.code && !force) {
  330.                 reslove(userInfo.code);
  331.                 return;
  332.             }
  333.             wx.login({
  334.                 success(res) {
  335.                     wx.code = res.code;
  336.                     reslove(res.code);
  337.                 },
  338.                 fail(res) {
  339.                     console.log(res);
  340.                     reject(res);
  341.                 }
  342.             });
  343.         }).then(function(code) {
  344.             if (!force && userInfo.data) return userInfo.data;
  345.             return new Promise(function(reslove, reject) {
  346.                 wx.getUserInfo({
  347.                     success(res) {
  348.                         reslove(res);
  349.                     },
  350.                     fail(res) {
  351.                         reject(res);
  352.                     }
  353.                 });
  354.             });
  355.         }).then(
  356.             function(res) {
  357.                 if (!force && userInfo.data) return userInfo.data;
  358.                 return userInfo.requestLogin(res, userInfo.code);
  359.             },
  360.             function(res) {
  361.                 console.log(res);
  362.                 _alert("登录失败,请重新登录")
  363.                     .then(res => {
  364.                         getUserInfo(callback, true);
  365.                     });
  366.                 throw new Error("login fail:" + res);
  367.             }
  368.         ).then(function(res) {
  369.             userInfo.data = res;
  370.             return callback(res) || res;
  371.         });
  372.     };
  373. }
  374. /**
  375. * 支付
  376. * @param  {[type]} payParams [description]
  377. * @return {[type]}           [description]
  378. */
  379. function payment(payParams) {
  380.     return new Promise(function(fulfill, reject) {
  381.         payParams.success = function(res) {
  382.             console.log(res);
  383.             fulfill(res);
  384.         };
  385.         payParams.fail = function(res) {
  386.             console.log(res);
  387.             reject(res);
  388.         };
  389.         console.log(payParams);
  390.         wx.requestPayment(payParams);
  391.     });
  392. }
  393. /**
  394. * 上传文件
  395. * @param  {[type]} opt [description]
  396. * @return {[type]}     [description]
  397. */
  398. function uploadFile(uploadFileConfig) {
  399.     const DEFAULT_UPLOAD_CONFIG = {
  400.         root: "",
  401.         defaultURL: "",
  402.         resloveStatus: noop,
  403.         requestParams: {
  404.             header: {},
  405.             name: ""
  406.         }
  407.     };
  408.     uploadFileConfig = assign({}, DEFAULT_UPLOAD_CONFIG, uploadFileConfig);
  409.     return function(options) {
  410.         return new Promise(function(fulfill, reject) {
  411.             options = assign({}, uploadFileConfig.requestParams, options);
  412.             options.url = options.url ? uploadFileConfig.root + options.url : uploadFileConfig.root + uploadFileConfig.defaultURL;
  413.             options.success = function(res) {
  414.                 let fileData;
  415.                 try {
  416.                     fileData = JSON.parse(res.data);
  417.                 } catch (e) {
  418.                     reject(e);
  419.                 }
  420.                 if (uploadFileConfig.resloveStatus(fileData)) {
  421.                     fulfill(fileData);
  422.                 } else {
  423.                     reject(fileData);
  424.                 }
  425.             };
  426.             options.fail = function(res) {
  427.                 console.log(res);
  428.                 reject(res);
  429.             };
  430.             wx.uploadFile(options);
  431.         });
  432.     };
  433. }
  434. exports.pubsub = {
  435.   cache : {},
  436.   $on () {},
  437.   $emit () {}
  438. };





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。