当前位置:   article > 正文

微信小程序教学第二章(含视频):小程序中级实战教程之预备篇 - 提取util公用方法...

微信小程序教学第二章(含视频):小程序中级实战教程之预备篇 - 提取util公用方法...

iKcamp官网:www.ikcamp.com

访问官网更快阅读全部免费分享课程:《iKcamp出品|全网最新|微信小程序|基于最新版1.0开发者工具之初中级培训教程分享》。 包含:文章、视频、源代码

第二章:小程序中级实战教程之预备篇

本文配套视频地址 v.qq.com/x/page/m055…

util公共方法

开始前请把 ch2-2 分支中的 code/ 目录导入微信开发工具


在这一章中,我们会在util目录新建 3 个文件,这些文件分别提供了一些常用的函数,变量,已便我们在不同的页面中使用

  1. ├── utils/
  2. │ ├─ config.js
  3. │ ├─ index.js
  4. │ ├─ mock.js
  5. 复制代码

Step 1.   config.js 配置常量

该文件存放了一些 const 常量(如开发环境,默认文案,默认图片等),将这些常量存在 core 这个对象中,最后通过 export default core 将 core 这个对象导出。由于只是存放一些配置常量,此处不再复述:

  1. 'use strict';
  2. const env = 'dev';// dev production
  3. /*
  4. * 默认接口出错弹窗文案
  5. * @type {string}
  6. */
  7. const defaultAlertMessage = '好像哪里出了小问题~ 请再试一次~';
  8. /*
  9. * 默认分享文案
  10. * @type {{en: string}}
  11. */
  12. const defaultShareText = {
  13. en: 'iKcamp英语-学英语口语听力四六级'
  14. };
  15. /*
  16. * 小程序默认标题栏文字
  17. * @type {string}
  18. */
  19. const defaultBarTitle = {
  20. en: 'iKcamp英语学习'
  21. };
  22. /*
  23. * 文章默认图片
  24. * @type {string}
  25. */
  26. const defaultImg = {
  27. articleImg: 'https://n1image.hjfile.cn/mh/2017/06/07/7e8f7b63dba6fa3849b628c0ce2c2a46.png',
  28. coverImg: 'https://n1image.hjfile.cn/mh/2017/06/07/7472c035ad7fe4b8db5d2b20e84f9374.png'
  29. };
  30. let core = {
  31. env: env,
  32. defaultBarTitle: defaultBarTitle['en'],
  33. defaultImg: defaultImg,
  34. defaultAlertMsg: defaultAlertMessage,
  35. defaultShareText: defaultShareText['en'],
  36. isDev: env === 'dev',
  37. isProduction: env === 'production'
  38. };
  39. export default core;
  40. 复制代码

Step 2.   mock.js 数据

该文件用来存放一些假数据,方便本地开发调试,如果你有 mock 服务器,当然更好

  1. const list = {
  2. data: [
  3. {
  4. articles: [
  5. {
  6. contentId: 1177432,
  7. cover: "https://n1image.hjfile.cn/mh/2017/06/26/9ffa8c56cfd76cf5159011f4017f022e.jpg",
  8. pubdate: "2017-06-27 00:45:00",
  9. title: "Quora精选:为什么聪明人总能保持冷静?"
  10. },
  11. {
  12. contentId: 1176561,
  13. cover: "https://n1image.hjfile.cn/mh/2017/06/26/0eb29c4c08e7be93f74ce9ce0fd5a25e.jpg",
  14. pubdate: "2017-06-27 00:30:00",
  15. title: "与时间有关的英语俚语(四)"
  16. },
  17. {
  18. contentId: 1161967,
  19. cover: "http://n1image.hjfile.cn/mh/2017/05/25/5d6ce79848cc81b800959383c35dd081.jpg",
  20. pubdate: "2017-06-27 00:15:00",
  21. title: "2017.5大学英语六级口语考试真题:看图论述“人与人之间的信任”"
  22. },
  23. {
  24. contentId: 1177828,
  25. cover: "https://n1image.hjfile.cn/mh/2017/06/26/c99a6d180367bf1a250d6e7c6c3083c6.jpg",
  26. pubdate: "2017-06-27 00:00:01",
  27. title: "亚马逊卖衣服有新招!新衣服试穿一周再付钱"
  28. }
  29. ],
  30. date: "2017-06-27"
  31. },
  32. {
  33. articles: [
  34. {
  35. contentId: 1175100,
  36. cover: "https://n1image.hjfile.cn/mh/2017/06/23/2490fdbcfc131c0e256546da4a03f1ac.jpg",
  37. pubdate: "2017-06-26 00:45:00",
  38. title: "双语美文:小时候的自己,真是傻得可爱"
  39. },
  40. {
  41. contentId: 1172434,
  42. cover: "https://n1image.hjfile.cn/mh/2017/06/19/57a8ef65ee53f5921657376fd3fe4a75.jpg",
  43. pubdate: "2017-06-26 00:30:00",
  44. title: "15个和money有关的习语,可别用错了"
  45. },
  46. {
  47. contentId: 1161968,
  48. cover: "http://n1image.hjfile.cn/mh/2017/05/25/2260fb0deb74734f5ec5a375423a6b52.jpg",
  49. pubdate: "2017-06-26 00:15:00",
  50. title: "2017年5月大学英语六级口语考试真题——小组讨论之扶老人是我们的责任吗?"
  51. },
  52. {
  53. contentId: 1161963,
  54. cover: "http://n1image.hjfile.cn/mh/2017/05/25/93228c5713545ef328e708ddb73e28a2.jpg",
  55. pubdate: "2017-06-26 00:15:00",
  56. title: "2017年5月大学英语六级口语考试——优秀领导的特质"
  57. }
  58. ],
  59. date: "2017-06-26"
  60. },
  61. {
  62. articles: [
  63. {
  64. contentId: 1175110,
  65. cover: "https://n1image.hjfile.cn/mh/2017/06/23/a5bf85e439696829a937accfd99f0eb7.jpg",
  66. pubdate: "2017-06-25 00:45:00",
  67. title: "Quora精选:什么样的人注定无法成功?"
  68. },
  69. {
  70. contentId: 1142849,
  71. cover: "https://n1image.hjfile.cn/mh/2017/06/22/faf544ccf3e4f9e8da4ee9d5d8fcc635.jpg",
  72. pubdate: "2017-06-25 00:30:00",
  73. title: "表达雌性动物和雄性动物的不同说法"
  74. },
  75. {
  76. contentId: 1161915,
  77. cover: "http://n1image.hjfile.cn/mh/2017/05/25/7778bd5547fa216db57cd87a78bd790d.jpg",
  78. pubdate: "2017-06-25 00:15:00",
  79. title: "2017年5月大学英语四级口语考试——如何用PPT展现一堂课"
  80. },
  81. {
  82. contentId: 1175101,
  83. cover: "https://n1image.hjfile.cn/mh/2017/06/23/045ed76502b0f1ccdaccdae827c17c2c.jpg",
  84. pubdate: "2017-06-25 00:00:00",
  85. title: "双语美文:总在不经意间,发觉自己渺小"
  86. }
  87. ],
  88. date: "2017-06-25"
  89. }
  90. ],
  91. message: "success",
  92. status: 0,
  93. time: null
  94. };
  95. const detail = {
  96. data: {
  97. agreeNum: 0,
  98. articleImage: "https://n1image.hjfile.cn/mh/2017/06/26/9ffa8c56cfd76cf5159011f4017f022e.jpg",
  99. author: "Quora用户",
  100. autoSummary: "Why do intelligent people seem calm all the time?为什么聪明人总能保持冷静?\r\n\r\n\t\r\n\r\n\tAnswer from @Domen Grabec来自@Domen Grabec的回答\r\n\r\n\tIf you can solve your problem, then what is the n...",
  101. cateId: 0,
  102. channelId: 1,
  103. commentCount: 2,
  104. content: '<p>\r\n\t<img src="https://n1image.hjfile.cn/mh/2017/06/26/47d852dce02d0b47d91efd05b9d450de.jpg" /></p>\r\n<p>\r\n\t<strong><div class="langs_en">Why do intelligent people seem calm all the time?</div><div class="langs_cn">为什么聪明人总能保持冷静?</div></strong></p>\r\n<p>\r\n\t&nbsp;</p>\r\n<p>\r\n\t<strong><div class="langs_en">Answer from @Domen Grabec</div><div class="langs_cn">来自@Domen Grabec的回答</div></strong></p>\r\n<p>\r\n\t<div class="langs_en">If you can solve your problem, then what is the need of worrying?</div><div class="langs_cn">如果你能解决问题,那何虑之有?</div></p>\r\n<p>\r\n\t<div class="langs_en">If you cannot solve it, then what is the use of worrying?</div><div class="langs_cn">如果你不能解决问题,那忧虑又有什么用呢?</div></p>\r\n<p>\r\n\t<div class="langs_en">And if you look at this <a href="http://dict.hjenglish.com/w/logically" class="hjdict" word="logically" target=_blank>logically</a> not being calm will only work to your disadvantage in many situations:</div><div class="langs_cn">如果你从逻辑的角度来看,不冷静只会起反效果,在很多情况下都一样:</div></p>\r\n<p>\r\n\t<div class="langs_en">There is an important exam coming up and you are freaking out. Panicking might confuse you, inhibit your learning and as a result you might perform worse on the exam.</div><div class="langs_cn">(比如)你正面临一场重要的考试,而你慌得不得了。你的惊慌只会让你思维混乱,它会妨碍你的学习,其结果就是你会在考试中发挥得更糟。</div></p>\r\n<p>\r\n\t<div class="langs_en">Someone is robbing you and you start to panic. You might get the robber nervous, and he might do something impulsive (like stab you) obviously worsening your position.</div><div class="langs_cn">(再比如)一个人正在抢劫你,而你开始慌了。你可能会让抢劫者变得紧张,而他可能就会做出些过激的事情(比如捅你一刀),显然这回让你的处境更糟。</div></p>\r\n<p>\r\n\t<div class="langs_en">You lead a group of people at work and are facing a heavy problem, or an impossible deadline. Well this is the time to inspire people and get the most out of them as possible. That should increase your chances of solving the problem. If you panic you might discourage them, and not only you, but your whole team shall underperform.</div><div class="langs_cn">(再比如)你正带领着一组人一起工作,并且正面临着一个严峻的问题,或者是一个不可能赶上的截止日期。好嘛,你现在需要做的是启发这些人,尽可能让他们做出成果;这会让你解决问题的概率更大一些。如果你慌了,你可能会打击到他们,于是不只是你,你的整个团队都会发挥不佳。</div></p>\r\n<p>\r\n\t<div class="langs_en">While you panic, your mind is having a hard time finding a solution to the problem. Even if the solution is only to stay calm and wait for the problem to pass.</div><div class="langs_cn">当你慌张的时候,你的大脑会很难找到解决问题的方法。而解决问题的方法很有可能只是冷静下来并等着问题自己过去。</div></p>\r\n<p>\r\n\t&nbsp;</p>\r\n<p>\r\n\t<strong><div class="langs_en">Answer from @Faith Paul</div><div class="langs_cn">来自@Faith Paul的回答</div></strong></p>\r\n<p>\r\n\t<div class="langs_en">Intelligent people think before they speak.</div><div class="langs_cn">聪明的人先想再说。</div></p>\r\n<p>\r\n\t<div class="langs_en">Intelligent people also think rationally.</div><div class="langs_cn">而且,聪明人的思维是理性的。</div></p>\r\n<p>\r\n\t<div class="langs_en">Instead of freaking out over every little thing, finding drama, or becoming a victim, intelligent people rationalize their problems.</div><div class="langs_cn">聪明人会理性地去分析问题,而不是在每个细枝末节上的慌神、制造情况、或怨天尤人。</div></p>\r\n<p>\r\n\t<div class="langs_en">Intelligent people don&#39;t prolong their problems. They end their suffering by doing what needs to be done in order for that problem to go away.</div><div class="langs_cn">聪明人不会让问题遗留下来。他们会做那些必要的事以解决问题。</div></p>\r\n<p>\r\n\t<div class="langs_en">Additionally, I&#39;ve noticed that intelligent people who are stressed find an outlet or take a nap. Bottling up anxiety or pointing fingers like many people do is just going to evoke more stress.</div><div class="langs_cn">还有,我发现聪明人在不堪重负的时候会找个发泄方式,或者小憩一下。很多其他人或把焦虑压制下来,或者在别人身上出气,而这只会让压力更重。</div></p>\r\n<p>\r\n\t<div class="langs_en">Obviously not all problems can be solved, but my point is that intelligent people handle stress differently.</div><div class="langs_cn">显然,并不是所有的问题都能被解决,我想表达的是:聪明人处理压力的方式时不一样的。</div></p>\r\n<p>\r\n\t<strong><br />\r\n\t</strong></p>\r\n<p>\r\n\t<strong><div class="langs_en">Answer from @Humberto Rada</div><div class="langs_cn">来自@Humberto Rada的回答</div></strong></p>\r\n<p>\r\n\t<div class="langs_en">This could be for several reasons, but one thing I noticed from highly intelligent friends who are calm is that they are able to entertain themselves.</div><div class="langs_cn">原因有很多,而我从我那些冷静的聪明朋友身上发现的一点是:他们有办法自娱自乐。</div></p>\r\n<p>\r\n\t<div class="langs_en">Yes that is right, they always got something to think about. </div><div class="langs_cn">对,就是这样,他们总有什么东西可以想。</div></p>\r\n<p>\r\n\t<div class="langs_en">Its like they enjoy their thoughts more than interacting with other people. </div><div class="langs_cn">好像他们觉得自己的思维比和人交流更有吸引力。</div></p>\r\n<p>\r\n\t<div class="langs_en">They are always elaborating on thoughts so they are busy with themselves.</div><div class="langs_cn">他们总是在细细揣摩自己的想法,所以他们自己一个人忙着呢。</div></p>\r\n<p>\r\n\t&nbsp;</p>\r\n<p>\r\n\t(翻译:能猫)</p>\r\n<p class="declaration">\r\n\t声明:本双语文章的中文翻译系iKcamp英语原创内容,转载请注明出处。中文翻译仅代表译者个人观点,仅供参考。如有不妥之处,欢迎指正。</p>\r\n',
  105. contentId: 1177432,
  106. editorName: "能猫",
  107. isBest: "Y",
  108. langs: "en ",
  109. langsCate: 1043,
  110. langsParentCate: 1040,
  111. lastUpdateTime: "2017-06-27 00:45:00.530",
  112. link: "",
  113. maxPageNum: 1,
  114. newTitle: "",
  115. picName: "",
  116. reviewFlag: 0,
  117. sourceLink: "",
  118. sourceName: "Quora",
  119. sourceType: 0,
  120. sparePic: "",
  121. subTitle: "",
  122. subjectId: 0,
  123. summary: "为什么有些人总是有办法冷静地面对一切?",
  124. tags: "智力|职场|学习|双语阅读|励志人生|实用热门|quora|微信热门",
  125. title: "Quora精选:为什么聪明人总能保持冷静?",
  126. totalView: 112
  127. },
  128. message: "success",
  129. status: 0,
  130. time: null
  131. };
  132. export {
  133. detail,
  134. list
  135. }
  136. 复制代码

Step 3.   增加 index.js 主入口文件

index.js 文件中,我们会增加一些公用的函数方法,比如对网络请求封装、开发环境下 log 日志、本地存储等

首先,我们把配置信息 config.js 和假数据 mock.js 引进来,并正常导出

  1. 'use strict'
  2. import Promise from '../lib/promise'
  3. import config from './config'
  4. import * as Mock from './mock'
  5. let util = {
  6. }
  7. export default util
  8. 复制代码

第二行代码:

  1. import Promise from '../lib/promise'
  2. 复制代码

这一段代码的作用是引入一个实现 Promise 的 第三方工具库,这样我们就可以在小程序中使用 Promise 方法来解决 回调地狱 的问题。

注意: 在新版本的小程序中已经支持了原生 Promise 方法

下面我们开始对 util 对象进行公用方法扩展封装: 增加 log 控制台调试功能

如果环境配置为dev环境,则打印参数内容

  1. let util = {
  2. isDEV: config.isDev,
  3. log(){
  4. this.isDEV && console.log(...arguments)
  5. }
  6. }
  7. 复制代码

封装 alert 弹出窗口

由于开发环境中,经常需要查看一些对象信息,所以增加了 object 类型解析

  1. let util = {
  2. // 此处省略部分代码
  3. alert(title = '提示', content = config.defaultAlertMsg) {
  4. if ('object' === typeof content){
  5. content = this.isDEV && JSON.stringify(content) || config.defaultAlertMsg
  6. }
  7. wx.showModal({
  8. title: title,
  9. content: content
  10. })
  11. }
  12. }
  13. 复制代码

wx.showModal 是微信官方提供的 api 方法,具体用法可 查阅文档

封装本地缓存数据的读取功能

wx.getStorage 文档地址
wx.setStorage 文档地址

  1. let util = {
  2. // 此处省略部分代码
  3. getStorageData(key, cb) {
  4. let self = this;
  5. // 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口
  6. wx.getStorage({
  7. key: key,
  8. success (res) {
  9. cb && cb(res.data);
  10. },
  11. fail (err) {
  12. let msg = err.errMsg || '';
  13. if( /getStorage:fail/.test(msg) ) {
  14. self.setStorageData(key)
  15. }
  16. }
  17. })
  18. },
  19. setStorageData(key, value = '', cb) {
  20. wx.setStorage({
  21. key: key,
  22. data: value,
  23. success() {
  24. cb && cb();
  25. }
  26. })
  27. }
  28. }
  29. 复制代码

上一篇-微信小程序教学第二章:小程序中级实战教程之预备篇 - 项目结构设计 |基于最新版1.0开发者工具

下一篇中,我们会把网络请求封装起来,并增加本地 mock 功能

iKcamp原创新书《移动Web前端高效开发实战》已在亚马逊、京东、当当开售。


相关文章: 听说 2017 你想写前端? 前端开发者指南(2017) 翻译连载 |《你不知道的JS》姊妹篇 | JavaScript 轻量级函数式编程 翻译 | 关键CSS和Webpack: 减少阻塞渲染的CSS的自动化解决方案

iKcamp最新活动

报名地址:www.huodongxing.com/event/54099…

“天天练口语”小程序总榜排名第四、教育类排名第一的研发团队,面对面沟通交流。


2019年,iKcamp原创新书《Koa与Node.js开发实战》已在京东、天猫、亚马逊、当当开售啦!

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号