使用 WebApi 交互打造原生的微信小程序 - 圖靈小書架
目錄
- 介紹
- 源碼地址
- 掃一掃體驗
- 代碼分析
- 其它相關信息(互聯網搜集)
介紹
定時抓取圖靈社區官網的首頁、最熱、推薦和最新等欄目的相關圖書信息進行展示,並且可以下載相關的 PDF 進行查閱...
主要功能
源碼地址
源碼地址1:https://github.com/liqingwen2015/ituring_small_bookshelf
源碼地址2:https://gitee.com/liqingwen/ituring_small_bookshelf
使用說明:
- 打開微信開發者工具;
- 路徑引入 src 文件夾;
- 輸入 APPID 和文件名即可;
- 本地不需要配置服務器地址,自動連接我的 WebAPI 接口資源,低成本配置;
不過使用 git,我有一個這樣的擔憂:用了5年GIT,原來分支合並是這樣協作的。假設團隊3個人。 領導開創一個分支。 我和另外一個同事在領導的分支下創建一個新分支。 然后 我們各自開發。 有新功能就 去拉取 並將領導的分支合並到自己的分支。 這樣,我改的東西,和同事改的不會沖突。最后,GIT 導出我們的差異,通過 QQ 傳給領導。
-- 引用 https://my.oschina.net/lcsoft/tweet/17666900
掃一掃體驗
可以通過小程序(已上線)二維碼掃一掃,也可以在小程序中搜一下【圖靈小書架】進行體驗:
它真的非常小(輕量、快、占用內存小),接近 10 個頁面所占用的空間大小(代碼+圖片等)才100KB+。
代碼分析
結構簡析
config 文件夾(可選):存放配置信息;
images 文件夾(可選):存放圖片;
pages 文件夾:存放每個頁面信息;
utils 文件夾(可選):工具類存放;
app.js:項目的入口文件,如包含程序生命周期定義(頁面初始化、頁面渲染完成、頁面顯示、頁面隱藏和頁面關閉等);
app.json:全局配置文件,如頁面路徑, tabBar(導航、圖標和選中樣式等);
app.wxss:全局樣式配置文件,如每個頁面可以重用的樣式;
project.config.json:程序的配置文件,如項目名稱、微信開發工具配置(是否校驗合法域名、是否壓縮和樣式自動補全等);
為了方便統一管理 api 請求的地址,我統一在 config/config.js 中配置 api 的請求地址:
const key = require('const.js'); // 服務器域名 const baseUrl = key.urlPrefix.server; //const baseUrl = key.urlPrefix.local; //獲取首頁的圖書 const getBooksOfIndex = baseUrl + 'books/v1/index'; //獲取圖書列表 const getBooksByShowType = baseUrl + 'books/v1/list'; //獲取圖書 const getBook = baseUrl + 'books/v1/detail'; const saveUserInfo = baseUrl + 'account/v1/save'; const submitComment = baseUrl + 'comment/v1/submit'; const getComments = baseUrl + 'comment/v1/list'; module.exports = { getBooksOfIndex: getBooksOfIndex, getBooksByShowType: getBooksByShowType, getBook: getBook, saveUserInfo: saveUserInfo, submitComment: submitComment, getComments: getComments };
同時,也把一些靜態 const 變量統一存放在 config/const.js 中,方便管理和維護:
// Key 名 module.exports = { // 用戶標識 wxUserId: 'WxUserId', // 登錄標識 loginFlag: 'LoginFlag', // 圖標 icon: { success: 'success', loading: 'loading', none: 'none' }, // url 前綴 urlPrefix: { server: 'https://api.nidie.com.cn/api/', //服務器 local: 'http://localhost:57196/api/', //本地 test: 'http://localhost:57196/api/', //測試 file: 'https://download.nidie.com.cn/', //文件 image: 'http://www.ituring.com.cn/' //圖片 } };
Pages 文件夾簡析
這里通過 detail (圖書詳情頁)文件夾進行解析,從圖中可以看到的文件夾中包含:
- .json 后綴的 JSON 配置文件
- .wxml 后綴的 WXML 模板文件
- .wxss 后綴的 WXSS 樣式文件
- .js 后綴的 JS 腳本邏輯文件
detail.wxml:
<view> <block wx:if="{{showLoading}}"> <view class="donut-container"> <view class="donut"></view> </view> </block> <block wx:else> <view class="book-container bg-white"> <view class="book-info"> <image class="book-image" mode="scaleToFill" src="{{book.imageUrl}}"></image> <view class="book-desc"> <text class="book-main-text">{{book.name}}</text> <text class="book-text">{{book.author}}</text> <text class="book-text">¥ {{book.price}} 元</text> <view class="loading-container" wx:if="{{downloading}}"> <progress percent="{{downloadPercent}}" stroke-width="6" activeColor="#1aad19" backgroundColor="#cdcdcd" show-info /> </view> </view> </view> </view> <view class="comment-container"> <view class="comment-title"> <text>========== 簡介 ==========</text> </view> <view class="comment-area"> <block> <view class="comment-placeholder"> <text>{{book.intro}}</text> </view> </block> </view> </view> <!-- bottom button --> <view class="fixed-bottom block-full-width flex-container bg-white" wx:if="{{isAllowDownload}}"> <button class="full-button" type="primary" catchtap="download" data-id="{{bookInfo.id}}" data-name="{{bookInfo.name}}"> 隨書下載<text style="font-size:26rpx; color:gray">(已存在,則立即打開)</text> </button> </view> </block> </view>
該文件非常像我們所學過的 html 結構,只不過標簽替換為了小程序自己包裝的語義標簽而已。
detail.js
// 獲取服務器接口地址 const api = require('../../config/config.js'); const key = require('../../config/const.js'); const http = require('../../utils/http.js'); const file = require('../../utils/file.js'); const cache = require('../../utils/cache.js'); const tip = require('../../utils/tip.js'); Page({ data: { bookIsBuy: 0, downloading: false, book: {}, id: '', showLoading: true, isAllowDownload: false, //是否允許下載 isDownloading: false //下載中標識 }, // 獲取書籍 getBook: function (id) { let that = this; let key = `Book_${id}`; let val = cache.getSync(key); let obj = { showLoading: false }; if (val) { if (val.pdfUrl && val.pdfUrl.trim() !== '') { obj.isAllowDownload = true; } obj.book = val; that.setData(obj); return; } http.get(api.getBook + `/${id}`, function (data) { if (data.pdfUrl && data.pdfUrl.trim() !== '') { obj.isAllowDownload = true; } obj.book = data; that.setData(obj); cache.set(key, data); }); }, // 下載 download: function () { let that = this; if (that.data.isDownloading) { tip.showToast('下載中,請稍安勿躁!!!'); return; } let cachekey = `Book_PDF_${that.data.id}`; let path = cache.getSync(cachekey); if (!path) { that.setData({ isDownloading: true }); let pdfUrl = that.data.book.pdfUrl.split(','); http.downloadFile(key.urlPrefix.file + pdfUrl[0], function (filePath) { file.openDocument(filePath); cache.set(cachekey, filePath); }, function () { that.setData({ isDownloading: false }); }); tip.showToast('已經開始下載,下載完畢后將自動打開,請稍后!!!'); return; } file.openDocument(path); }, /** * 生命周期函數--監聽頁面加載 */ onLoad: function (options) { let that = this; let id = options.id; that.getBook(id); that.setData({ id: id }); }, });
里面的語法類似 VUE,WXML 中的動態數據均來自對應 Page 的 data,因為我把很多自己封裝的方法單獨放到 utils 文件夾和 config 文件夾中,在希望調用對應的方法時需要使用 require 函數將其引入,小程序有許多豐富的 API,代碼中就使用了如下載、請求 json 數組、提示彈出框和 localStorage 緩存等 API(含同步、異步)。
detail.json
{ "navigationBarTitleText": "詳情頁" }
這里只是對應導航頭文字進行了修改而已。
detail.wxss 樣式文件,並沒有太多可以說的,按照自己的 css 樣式進行編寫就好了。
其它相關信息(互聯網搜集)
PC 的 IDE、蘋果 IOS 和安卓 Android,它們的運行環境是存在差異,意味着不是所有提供的 API 都可以完全兼容。
見 https://developers.weixin.qq.com/miniprogram/dev/devtools/details.html#運行環境差異
小程序 - MINA 框架
微信團隊為小程序提供的框架命名為MINA應用框架。MINA框架通過封裝微信客戶端提供的文件系統、網絡通信、任務管理、數據安全等基礎功能,對上層提供一整套JavaScript API,讓開發者能夠非常方便地使用微信客戶端提供的各種基礎功能與能力,快速構建一個應用。
小程序 - 啟動運行機制
小程序 - 生命周期