In 2019, I participated in the development of several small program projects, which have been in the draft box. I will sort out and release them today, and I will add several versions to be updated when I do the small program projects later. Summary reflection, continuous improvement, hope to develop the habit of writing articles, fighting~
The official documentation
I. Overall project configuration and construction
- Page directory structure
├─ Behaviors # Public ├─ xx.js ├─ Bin # Node Script ├─ Template # Public Template ├─common # Public Library ├─ Icon # Iconfont ├─ Style # Public Style ├─ Components # Public Component ├─ Images # Static Images ├─ Node_modules # Use all the packages and their dependencies ├─package.json # .js # esLint Config Rule file ├─ Service # All Request Folder ├─ Request.js # Base Request Package ├─ApiConfig. Js # All APIS to Configure ├─ Homeservice.js # All home page request ├─util # Public Method Library ├─constant │ ├─ Promispromisy.js │ ├─ Pages │ ├─ Storage.js │ ├─ Storage.js │ ├─ Promisy.js │ ├─ Pages │ All development in this directory ├─home # page location, with the page name as a subfolderCopy the code
- App. Json configuration
The first page in the page array is the starting page entered by the applet first
If debug is true, debugging is enabled
{ "pages": [ "pages/transfer/transfer", "pages/memberHome/memberHome" ], "window": { "backgroundTextStyle": "Light", "navigationBarBackgroundColor" : "# FFF", "navigationBarTitleText" : "small application bar title", "navigationBarTextStyle" : "black" }, "networkTimeout": { "request": 30000, "downloadFile": 30000 }, "debug": true }Copy the code
- App.js entry general Settings
App({onLaunch() {const that = this /* Wx.getNetworkType ({success(res) {const NetworkType = res.net workType if (networkType = = = 'none') {that. GlobalData. IsConnected = false wxShowToast (' current no network ')}} }) /* wx.onNetworkStatusChange(function(res) {if (! Res. IsConnected) {that. GlobalData. IsConnected = false wxShowToast (' network has broken ')} else {that. GlobalData. IsConnected = true */ if (wx.caniuse ('getUpdateManager')) {// Base library 1.9.90 start support, Low version to do compatible with const updateManager = wx. GetUpdateManager () updateManager. OnCheckForUpdate (function (result) {if (result. HasUpdate) {/ / a new version updateManager. OnUpdateReady (function () {/ / download the new version of wx showModal ({title: 'Update hint ', content:' The new version has been downloaded, please restart the application. ', success: Function (result) {if (result.confirm) { Call applyUpdate use new version and restart updateManager. ApplyUpdate ()}}})}) updateManager. OnUpdateFailed (function () {/ / new version download failed Wx. showModal({title: 'there is a new version ~', content: })})})} else {wx.showmodal ({title: wx.showmodal ({title: wx.showmodal ({title: wx.showmodal ({title: wx.showmodal ({title: wx.showmodal)})} 'Warm tips ', Content:' The current wechat version is too early to use this application, please upgrade to the latest wechat version and try again. '})}}, onShow() {}, globalData: {isConnected: true}})Copy the code
- Gitignore configuration (upload gitignore file)
.idea/ .vscode/ node_modules/ npm-debug.log .DS_Store *.wxss ! vantWeapp/*/*.wxss package-lock.jsonCopy the code
Second, transfer page design
Ideas: the transfer page as the home page of the small program, specifically dealing with login, and for different environments, different scenarios, user identity in the small program to do the corresponding page forward
Note:
- Communicate with the back end the address parameters of the applet from the template message
- Note the difference between wechat applet official entry scene value
*/ onLoad: function(options) {console.log('transfer options: ', options) // Enter page parameter if (ENV! Wx. RedirectTo ({url: 'MOCK') {this.loginAndreDirect (options)} else {// MOCK directly to wx. RedirectTo ({url: '/ pages/memberHome/memberHome'}}}), according to the options after login / * * * WeChat jump of the corresponding page * @ param} {* * / loginAndRedirect options: Function (options) {const that = this promise.resolve ().then() => {wx.showloading ({title: '... ', mask: True})}).then(() => {// Check the login status return loginservice.checkLogin ().catch(() => {console.log('not login') return Loginservice.login ()})}). Catch ((err) => {wx.showmodal ({title: 'prompt ', Content: err. Message, showCancel: false, confirmText: 'retry' success(res) { if (res.confirm) { that.loginAndRedirect(options) } } }) throw err }) .then(() => { That.redirecttarget (options)}).finally(() => {wx.hideloading ()})}, function(options) { if (!! options && options.scene && String(options.scene).length > 4) { const scene = String(options.scene) const t = Scene. The substring (0, 4) let the url = 'switch (+ t) {case 1000: / / url = ` / pages/goods detail 】 【 goodDetail/goodDetail? Scene = {value} ` break case 1001: / / url = 'head delivery code 】 【 / pages/memberDeliveryDetail/memberDeliveryDetail? id={value}' break default: WxShowToast (' no matching page ') throw new Error(' no matching page ') break} if (url.indexof ('{value}') > -1) {try {url = url.replace('{value}', scene.substring(4, Scene.length))} catch (e) {throw e}} wx.redirectto ({url})} else {// Normal flow const accessToken = getStorageSync(ACCESSTOKENINFO) if (! AccessToken) throw new Error (' no login information, please try again later). Wx redirectTo ({url: '/ pages/headIndex headIndex})}}Copy the code
3. Sorting out the login process
Official small program login introduction
Official UnionID mechanism
Iv. Processing of necessary events on the page and upgrading of experience
Event method API
/ / onPullDownRefresh: Function () {Promise. Resolve (). Then (() = > {wx. ShowNavigationBarLoading () / / in the title bar displays the load / / dropdown - reset page data refresh!!! this.setData({pageNum: 1, list: [], isNextPage: True})}). Then (() = > {enclosing getInitData () / / load the data to initialize}), then (() = > {wx. HideNavigationBarLoading () / / complete stop loading Wx.stoppulldownrefresh () // Stop pull-down refresh}). Catch (err => {console.log(' pull-down refresh failed :', err)})}Copy the code
Handle the change constants and domain name configuration of mock, dev, test and prod environments
# # # to be updated
Encapsulation of interface service requests
# # # to be updated
Vii. Turn wechat API into Promise design
# # # to be updated
Viii. Introduction of third-party libraries (UI component library, plug-in library)
# # # to be updated
Nine, the introduction of ali icon library method
# # # to be updated
Applets cache mechanism
# # # to be updated
Eleventh, small program payment function realization
# # # to be updated
12. The small program message push function realizes the collection and processing mechanism of &&formId
Template message push Reference 1
For details, see 2
Thirteen, guide the two ways to realize the public number
Note: 1, the payment is successful, only automatic attention service number, subscription number can not!!
Guide attention to the public summary
The official-Account component concerns
Fourteen, small program long press to save pictures, upload, download file functions
15. Mini-program authorization mechanism
Small program running mechanism + update mechanism
Small program official website introduction
Simplification techniques in small programs
- Install gulp, real-time compile. Less is.wxss
- Write node scripts to quickly and efficiently create page initialization template pages and COM initialization component template pages
Seventeen, step on the pit point ~
- 1, small program development version, experience version, official version cache storage data conflict
Solution: Use environment variables to differentiate stored keys
import { ENV } from '.. /utils/constant' // Export const getStorageSync = (key) => {return '${ENV}-${key}'} export const getStorageSync = (key) => { Return wx.getStorageSync(getKey)} export const setStorageSync = (key, data) => { wx.setStorageSync(getKey(key), Export const removeStorageSync = (key) => {wx.removeStoragesync (getKey)}Copy the code
- 2, the official version of the audit encountered pit
1, login requires account password login, need to provide a test account password for audit personnel to use
2, if the content of the home page is too simple (generally there is no content, just deal with login transfer), the best version of the remarks
Small program audit step pit
Eighteen, small program picture optimization
Small program picture lazy loading 1
Small program picture lazy loading 2