§ util 公共方法

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


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

  ├── utils/             
  │   ├─ config.js
  │   ├─ index.js
  │   ├─ mock.js


Step 1.   config.js 配置常量

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

  'use strict';
  const env = 'dev';// dev production
  /*
   * 默认接口出错弹窗文案
   * @type {string}
   */
  const defaultAlertMessage = '好像哪里出了小问题~ 请再试一次~';
  /*
   * 默认分享文案
   * @type 
   */
  const defaultShareText = {
      en: 'iKcamp英语-学英语口语听力四六级'
  };
  /*
   * 小程序默认标题栏文字
   * @type {string}
   */
  const defaultBarTitle = {
      en: 'iKcamp英语学习'
  };
  /*
   * 文章默认图片
   * @type {string}
   */
  const defaultImg = {
      articleImg: 'https://n1image.hjfile.cn/mh/2017/06/07/7e8f7b63dba6fa3849b628c0ce2c2a46.png',
      coverImg: 'https://n1image.hjfile.cn/mh/2017/06/07/7472c035ad7fe4b8db5d2b20e84f9374.png'
  };
  let core = {
      env: env,
      defaultBarTitle: defaultBarTitle['en'],
      defaultImg: defaultImg,
      defaultAlertMsg: defaultAlertMessage,
      defaultShareText: defaultShareText['en'],
      isDev: env === 'dev',
      isProduction: env === 'production'
  };
  export default core;


Step 2.   mock.js 数据

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

  const list = {
    data: [
      {
        articles: [
          {
            contentId: 1177432,
            cover: "https://n1image.hjfile.cn/mh/2017/06/26/9ffa8c56cfd76cf5159011f4017f022e.jpg",
            pubdate: "2017-06-27 00:45:00",
            title: "Quora精选:为什么聪明人总能保持冷静?"
          },
          {
            contentId: 1176561,
            cover: "https://n1image.hjfile.cn/mh/2017/06/26/0eb29c4c08e7be93f74ce9ce0fd5a25e.jpg",
            pubdate: "2017-06-27 00:30:00",
            title: "与时间有关的英语俚语(四)"
          },
          {
            contentId: 1161967,
            cover: "http://n1image.hjfile.cn/mh/2017/05/25/5d6ce79848cc81b800959383c35dd081.jpg",
            pubdate: "2017-06-27 00:15:00",
            title: "2017.5大学英语六级口语考试真题:看图论述“人与人之间的信任”"
          },
          {
            contentId: 1177828,
            cover: "https://n1image.hjfile.cn/mh/2017/06/26/c99a6d180367bf1a250d6e7c6c3083c6.jpg",
            pubdate: "2017-06-27 00:00:01",
            title: "亚马逊卖衣服有新招!新衣服试穿一周再付钱"
          }
        ],
        date: "2017-06-27"
      },
      {
        articles: [
          {
            contentId: 1175100,
            cover: "https://n1image.hjfile.cn/mh/2017/06/23/2490fdbcfc131c0e256546da4a03f1ac.jpg",
            pubdate: "2017-06-26 00:45:00",
            title: "双语美文:小时候的自己,真是傻得可爱"
          },
          {
            contentId: 1172434,
            cover: "https://n1image.hjfile.cn/mh/2017/06/19/57a8ef65ee53f5921657376fd3fe4a75.jpg",
            pubdate: "2017-06-26 00:30:00",
            title: "15个和money有关的习语,可别用错了"
          },
          {
            contentId: 1161968,
            cover: "http://n1image.hjfile.cn/mh/2017/05/25/2260fb0deb74734f5ec5a375423a6b52.jpg",
            pubdate: "2017-06-26 00:15:00",
            title: "2017年5月大学英语六级口语考试真题——小组讨论之扶老人是我们的责任吗?"
          },
          {
            contentId: 1161963,
            cover: "http://n1image.hjfile.cn/mh/2017/05/25/93228c5713545ef328e708ddb73e28a2.jpg",
            pubdate: "2017-06-26 00:15:00",
            title: "2017年5月大学英语六级口语考试——优秀领导的特质"
          }
        ],
        date: "2017-06-26"
      },
      {
        articles: [
          {
            contentId: 1175110,
            cover: "https://n1image.hjfile.cn/mh/2017/06/23/a5bf85e439696829a937accfd99f0eb7.jpg",
            pubdate: "2017-06-25 00:45:00",
            title: "Quora精选:什么样的人注定无法成功?"
          },
          {
            contentId: 1142849,
            cover: "https://n1image.hjfile.cn/mh/2017/06/22/faf544ccf3e4f9e8da4ee9d5d8fcc635.jpg",
            pubdate: "2017-06-25 00:30:00",
            title: "表达雌性动物和雄性动物的不同说法"
          },
          {
            contentId: 1161915,
            cover: "http://n1image.hjfile.cn/mh/2017/05/25/7778bd5547fa216db57cd87a78bd790d.jpg",
            pubdate: "2017-06-25 00:15:00",
            title: "2017年5月大学英语四级口语考试——如何用PPT展现一堂课"
          },
          {
            contentId: 1175101,
            cover: "https://n1image.hjfile.cn/mh/2017/06/23/045ed76502b0f1ccdaccdae827c17c2c.jpg",
            pubdate: "2017-06-25 00:00:00",
            title: "双语美文:总在不经意间,发觉自己渺小"
          }
        ],
        date: "2017-06-25"
      }
    ],
    message: "success",
    status: 0,
    time: null
  };

  const detail = {
    data: {
      agreeNum: 0,
      articleImage: "https://n1image.hjfile.cn/mh/2017/06/26/9ffa8c56cfd76cf5159011f4017f022e.jpg",
      author: "Quora用户",
      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...",
      cateId: 0,
      channelId: 1,
      commentCount: 2,
      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',
      contentId: 1177432,
      editorName: "能猫",
      isBest: "Y",
      langs: "en   ",
      langsCate: 1043,
      langsParentCate: 1040,
      lastUpdateTime: "2017-06-27 00:45:00.530",
      link: "",
      maxPageNum: 1,
      newTitle: "",
      picName: "",
      reviewFlag: 0,
      sourceLink: "",
      sourceName: "Quora",
      sourceType: 0,
      sparePic: "",
      subTitle: "",
      subjectId: 0,
      summary: "为什么有些人总是有办法冷静地面对一切?",
      tags: "智力|职场|学习|双语阅读|励志人生|实用热门|quora|微信热门",
      title: "Quora精选:为什么聪明人总能保持冷静?",
      totalView: 112
    },
    message: "success",
    status: 0,
    time: null
  };

  export {
      detail,
      list
  }


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

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

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

  'use strict'
  import Promise from '../lib/promise'
  import config from './config'
  import * as Mock from './mock'

  let util = {
    
  }
  export default util


第二行代码:

  import Promise from '../lib/promise'

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

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

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

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

let util = {
  isDEV: config.isDev,
  log(){
    this.isDEV && console.log(...arguments)
  }
}


封装 alert 弹出窗口

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

let util = {
  // 此处省略部分代码
  alert(title = '提示', content = config.defaultAlertMsg) {
    if ('object' === typeof content){
      content = this.isDEV && JSON.stringify(content) || config.defaultAlertMsg
    }
    wx.showModal({
      title: title,
      content: content
    })
  }
}


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

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

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

let util = {
  // 此处省略部分代码
  getStorageData(key, cb) {
    let self = this;

    // 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口
    wx.getStorage({
      key: key,
      success (res) {
        cb && cb(res.data);
      }, 
      fail (err) {
        let msg = err.errMsg || '';
        if( /getStorage:fail/.test(msg) ) {
          self.setStorageData(key)
        }
      }
    })
  },
  setStorageData(key, value = '', cb) {
    wx.setStorage({
      key: key,
      data: value,
      success() {
        cb && cb();
      }
    })
  }
}


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

返回大纲

上一篇:项目结构设计

下一篇:封装网络请求及 mock 数据