微信小程序教學第二章(含視頻):小程序中級實戰教程之預備篇 - 提取util公用方法

iKcamp官網:www.ikcamp.comhtml

訪問官網更快閱讀所有免費分享課程:《iKcamp出品|全網最新|微信小程序|基於最新版1.0開發者工具之初中級培訓教程分享》。 包含:文章、視頻、源代碼前端

第二章:小程序中級實戰教程之預備篇

本文配套視頻地址 v.qq.com/x/page/m055…react

util公共方法

開始前請把 ch2-2 分支中的 code/ 目錄導入微信開發工具git


在這一章中,咱們會在util目錄新建 3 個文件,這些文件分別提供了一些經常使用的函數,變量,已便咱們在不一樣的頁面中使用github

├── 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 {{en: string}} */
  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 引進來,並正常導出api

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

  let util = {
    
  }
  export default util
複製代碼

第二行代碼:promise

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();
      }
    })
  }
}
複製代碼

上一篇-微信小程序教學第二章:小程序中級實戰教程之預備篇 - 項目結構設計 |基於最新版1.0開發者工具

下一篇中,咱們會把網絡請求封裝起來,並增長本地 mock 功能

iKcamp原創新書《移動Web前端高效開發實戰》已在亞馬遜、京東、噹噹開售。


相關文章: 據說 2017 你想寫前端? 前端開發者指南(2017) 翻譯連載 |《你不知道的JS》姊妹篇 | JavaScript 輕量級函數式編程 翻譯 | 關鍵CSS和Webpack: 減小阻塞渲染的CSS的自動化解決方案

iKcamp最新活動

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

「每天練口語」小程序總榜排名第4、教育類排名第一的研發團隊,面對面溝通交流。


2019年,iKcamp原創新書《Koa與Node.js開發實戰》已在京東、天貓、亞馬遜、噹噹開售啦!

相關文章
相關標籤/搜索