


How to develop WeChat mini programs like a duck in water
Mar 30, 2021 am 10:51 AM? I have always wanted to write a related article to summarize and record the development of WeChat mini programs, but I have been suffering from procrastination and have not started writing. The weather has been nice recently, so I found a free time. I will output this article in the afternoon (it seems to have nothing to do with the weather), then let’s get started!
Note: This article assumes that developers have a certain grammatical foundation in WeChat applet development. Mini Program Development Document
Related free learning recommendations: WeChat Mini Program Development
WeChat Summary of Mini Programs
? During the development process of WeChat Mini Programs, it is not difficult to find that WeChat Mini Programs have well encapsulated many underlying APIs for the convenience of developers, such as for interface requestswx.request()
, wx.switchTab, wx.navigateTo···
, etc. for routing jumps and page navigation. Although it simplifies development to a certain extent, it is still not enough for the systematic construction of project engineering. Therefore, after comparing my previous experience in developing projects based on Vue and my own development habits, I summarized the following 3 points for reference:
1. Unified management of global variables and configuration information;
2. Encapsulation of route guard related APIs:
vue-router
router.beforeEach()
androuter.afterEach()
are really good;3. The interface requests public information for further extraction and encapsulation;
4. The request and response interception API of the encapsulated interface:
axios.interceptors.request.use()
andaxios of
axios. interceptors.response.use()
Everyone who has used it says it is good;
Starting from the above four points, standardizing and optimizing the WeChat applet initialization project can greatly improve Development efficiency and project maintenance management. The benefits of encapsulation are not only reflected in the convenience of calling, but also in the convenience of management. At the same time, public operations are processed centrally, which greatly reduces complex and repetitive code.
1. Project Initialization
? Create a new WeChat applet project, and create the following directories and files under the project:
- config folder: Unified management of configurable information and variables;
- erroList.js: Interface error reporting
Error code
Matching list file; - globalData.js:
Global variables
Unified management files (equivalent to vuex); - keys.js: Configurable system information management files (global constant naming, etc.);
- erroList.js: Interface error reporting
- pages folder: small Program page file management folder (one sub-folder directory for each page);
- router folder: routing management file;
- router.js: WeChat applet
5 A kind of routing navigation
api encapsulation; - routerConfig.js: page routing name and path matching configuration file;
- routerFilter.js: route prefix
interception
encapsulation ;
- router.js: WeChat applet
- servers file: interface request service management folder;
- apis folder: request request encapsulation management and interface api configuration management folder;
- request.js:
Promise
encapsulation ofwx.request
; - xxx.js: The interface management file of the corresponding module;
- request.js:
- requestFilter.js: Interface
Request and response interception
Encapsulation file;
##Others are initialization default files; - apis folder: request request encapsulation management and interface api configuration management folder;
2. Route jump and route guard encapsulation
1. Route jump encapsulation
? WeChat The official documentation of the mini program provides developers with 5 routing APIs, each of which has its own special usage: Encapsulate as follows: WeChat applet route jump finally corresponds topush, replace, pop, relaunch, switchTab
;routes corresponds to the configuration of the routing path in routeConfig.js;
Corresponds to the routerFilter.js file, which processes the logic before route jump; routeConfig.js (needs to be added manually after each new page):
<pre class="brush:php;toolbar:false">export?const?routes?=?
??{
????INDEX:?"/pages/index/index",
????TEST:?"/pages/test/test",
??}export?default?{...routes};</pre>
routerFilter.js: <pre class="brush:php;toolbar:false">export?default?()?=>?{
??···??//路由跳轉(zhuǎn)前邏輯處理}</pre>
router.js (routerFilter is responsible for processing public operations before routing jumps, and processing public operations after routing jumps in success and fail):
import?routes?from?"../router/routerConfig";import?routerFilter?from?"./routerFilter"/** ?*?對wx.navigateTo的封裝 ?*?@param?{路由}?path? ?*?@param?{參數(shù)}?params? ?*?@param?{事件}?events? ?*/const?push?=?(path,?params,?events)?=>?{ ??routerFilter() ??wx.navigateTo({ ????url:?routes[path]?+?`?query=${JSON.stringify(params)}`, ????events:?events, ????success(res)?{ ??????console.log(res); ????}, ????fail(err)?{ ??????console.log(err); ????} ??})}/** ?*?對wx.redirectTo的封裝 ?*?@param?{路由}?path? ?*?@param?{參數(shù)}?params? ?*/const?replace?=?(path,?params)?=>?{ ??routerFilter() ??wx.redirectTo({ ????url:?routes[path]?+?`?query=${JSON.stringify(params)}`, ????success(res)?{ ??????console.log(res); ????}, ????fail(err)?{ ??????console.log(err); ????} ??})}/** ?*?對wx.navigateBack的封裝 ?*?@param?{返回的層級}?number? ?*/const?pop?=?(number)?=>?{ ??routerFilter() ??wx.navigateBack({ ????delta:?number, ????success(res)?{ ??????console.log(res); ????}, ????fail(err)?{ ??????console.log(err); ????} ??})}/** ?*?對wx.reLaunch的封裝 ?*?@param?{路由}?path? ?*?@param?{參數(shù)}?params? ?*/const?relaunch?=?(path,?params)?=>?{ ??routerFilter() ??wx.reLaunch({ ????url:?routes[path]?+?`?query=${JSON.stringify(params)}`, ????success(res)?{ ??????console.log(res); ????}, ????fail(err)?{ ??????console.log(err); ????} ??})}/** ?*?對tabbar的封裝 ?*?@param?{路由}?path? ?*/const?switchTab?=?(path)?=>?{ ??routerFilter() ??wx.switchTab({ ????url:?routes[path], ????success(res)?{ ??????console.log(res); ????}, ????fail(err)?{ ??????console.log(err); ????} ??})}module.exports?=?{ ??push, ??replace, ??pop, ??relaunch, ??switchTab}2, Global registration and use
Global registration of the encapsulated routing api in
app.js: import?router??from?"./router/router.js"//全局注冊wx.router?=?router
Use in page logic:
//index頁面跳轉(zhuǎn)test頁面?gotoTest(){ ???wx.router.push("TEST")}
3. Interface request Promise encapsulation
?For the same project, many parameters in the WeChat applet api
wx.request() are the same , if used directly, these repeated parameters need to be copied over and over again. Although copying is very simple, when a parameter changes, all interfaces need to be found and modified one by one, which is laborious to maintain and uncomfortable to watch; ??借鑒 以user.js為例: index頁面調(diào)用: 四、接口的請求和響應(yīng)攔截封裝 ?? requestFilter.js中可以做很多對報(bào)錯(cuò)的處理,這里用一個(gè)簡單的toast處理示范下: 對報(bào)錯(cuò)進(jìn)行統(tǒng)一處理需要明確數(shù)據(jù)規(guī): 五、全局?jǐn)?shù)據(jù)管理 ??對于數(shù)據(jù)的管理在小項(xiàng)目的開發(fā)中顯得不那么重要,但是隨著項(xiàng)目越來越大,數(shù)據(jù)越來越多,一個(gè)很好的數(shù)據(jù)管理方案能夠有效地避免很多bug,這也是vuex能夠在vue生態(tài)中占有一席之地的原因。秉承著合理管理數(shù)據(jù)的原則,對于該封裝的數(shù)據(jù)堅(jiān)決封裝,對于該分模塊管理的配置堅(jiān)決分塊管理: 微信小程序中全局的數(shù)據(jù)管理放在 keys.js屬于個(gè)人開發(fā)中的習(xí)慣操作,將項(xiàng)目中可能用到的一些常量名稱在此集中管理起來,十分方便調(diào)用和修改維護(hù): 引入app.js: 在頁面代碼邏輯中可以通過 六、總結(jié) ??上述關(guān)于微信小程序開發(fā)的幾個(gè)方面都是在實(shí)踐中學(xué)習(xí)和總結(jié)的,技術(shù)層面的實(shí)現(xiàn)其實(shí)很容易,但是個(gè)人覺得開發(fā)規(guī)范項(xiàng)目工程構(gòu)建才是一個(gè)項(xiàng)目的重要基礎(chǔ);完善的規(guī)范能夠有效的提高開發(fā)效率和開發(fā)者之間非必要的 ??有需要源碼的可以關(guān)注微信公眾號 哇喔WEB 回復(fù) "wxmp"獲?。?/p>
??歡迎大家討論留言、進(jìn)行補(bǔ)充! 相關(guān)學(xué)習(xí)推薦:小程序開發(fā)教程axios
對請求的封裝,將wx.request()
封裝為Promise
形式豈不美哉:request.js:
import?formatError?from?"../requestFilter"const?app?=?getApp()/**
?*?接口請求封裝
?*?@param?{請求方式}?method?
?*?@param?{請求的url}?url?
?*?@param?{請求傳遞的數(shù)據(jù)}?data?
?*/const?request?=?(method,?url,?data)?=>?{
??//設(shè)置請求頭
??const?header?=?{
????···??}
??//promise封裝一層,使得調(diào)用的時(shí)候直接用then和catch接收
??return?new?Promise((resolve,?reject)?=>?{
????wx.request({
??????method:?method,
??????url:?app.globalData.host?+?url,?//完整的host
??????data:?data,
??????header:?header,
??????success(res)?{
????????//對成功返回的請求進(jìn)行數(shù)據(jù)管理和統(tǒng)一邏輯操作
????????···????????resolve(res.data)
??????},
??????fail(err)?{
????????wx.showToast({
??????????title:?'網(wǎng)絡(luò)異常,稍后再試!',
??????????mask:?true,
??????????icon:?'none',
??????????duration:?3000
????????})
??????}
????})
??})}export?default?request;
具體使用
import?request?from?"./request";//?獲取用戶openidexport?const?usrInfos?=?data?=>?request("POST",?"/user/usrInfos",?data);
//index.js//獲取應(yīng)用實(shí)例const?app?=?getApp()import?{?usrInfos?}?from?"../../servers/apis/user"Page({
??onLoad:?function?()?{
????//獲取用戶信息
????usrInfos({
??????uid:?"xxxx"
????})
??????.then(res?=>?{
????????console.log(res)
??????})
??????.catch(err?=>?{
????????console.log(err)
??????})
??}})
axios
的axios.interceptors.request.use()
和axios.interceptors.response.use()
分別對應(yīng)接口請求前的攔截處理和數(shù)據(jù)響應(yīng)后的攔截處理;根據(jù)這個(gè)原理我們對微信小程序的響應(yīng)也做攔截封裝,對接口請求返回錯(cuò)誤進(jìn)行統(tǒng)一管理輸出:request.js
import?formatError?from?"../requestFilter"const?app?=?getApp()···const?request?=?(method,?url,?data)?=>?{
??···??return?new?Promise((resolve,?reject)?=>?{
????wx.request({
??????···??????success(res)?{
????????//對成功返回的請求進(jìn)行數(shù)據(jù)管理和統(tǒng)一邏輯操作
????????if(res.statusCode?===?200){?//請求返回成功
??????????if(res.data?&&?res.data.code?===?"SUCCESS"){?//后端對接口請求處理成功,返回?cái)?shù)據(jù)給接口調(diào)用處
????????????resolve(res.data)??//then接收
??????????}else{ //后端對也請求判斷后認(rèn)為不合邏輯報(bào)錯(cuò)
????????????formatError(res)???//統(tǒng)一的報(bào)錯(cuò)處理邏輯
????????????reject(res.data)? //catch接收
??????????}?
????????}else{
??????????reject(res.data) //catch接收
????????}
??????},
??????fail(err)?{ //請求不通報(bào)錯(cuò)
????????wx.showToast({
??????????title:?'網(wǎng)絡(luò)異常,稍后再試!',
??????????mask:?true,
??????????icon:?'none',
??????????duration:?3000
????????})
??????}
????})
??})}export?default?request;
requestFilter.js
/**
?*?對接口返回的后端錯(cuò)誤進(jìn)行格式轉(zhuǎn)化
?*?@param?{接口成功返回的數(shù)據(jù)}?res?
?*/const?formatError?=?(err?=>{
??wx.showToast({
????title:?err.message,
????mask:?false,
????icon:?'none',
????duration:?3000
??})}export?default?formatError;
globalData.js
app.js
的globalData
屬性中,當(dāng)數(shù)據(jù)太多或者app.js邏輯太復(fù)雜時(shí),將全局?jǐn)?shù)據(jù)提取出來單獨(dú)管理的確是個(gè)好方案:export?default?{
??···
??host:?"http://www.wawow.xyz/api/test",?//接口請求的域名和接口前綴?
??hasConfirm:?""?//是否已經(jīng)有了confirm實(shí)例
??currentPage:?""
??···}
keys.js
export?default?{
??···??TOKEN:?"token",
??STORAGEITEM:?"test"
??···}
全局引用和注冊
import?router??from?"./router/router.js"import?keys?from?"./config/keys"import?globalData?from?"./config/globalData"//全局注冊wx.router?=?router
wx.$KEYS?=?keys//app.jsApp({
??//監(jiān)聽小程序初始化
??onLaunch(options)?{
????//獲取小程序初始進(jìn)入的頁面信息
????let?launchInfos?=?wx.getLaunchOptionsSync()
????//將當(dāng)前頁面路由存入全局的數(shù)據(jù)管理中
????this.globalData.currentPage?=?launchInfos.path??},
??···??//全局?jǐn)?shù)據(jù)存儲
??globalData:?globalData})
使用
app.globalData.host
,wx.$KEYS.TOKEN
方式進(jìn)行調(diào)用;扯皮
!合理的項(xiàng)目工程構(gòu)建能夠優(yōu)化開發(fā)邏輯,提高代碼邏輯易讀性,減少后期項(xiàng)目的管理時(shí)間,同時(shí)給予項(xiàng)目更大的擴(kuò)展性。
The above is the detailed content of How to develop WeChat mini programs like a duck in water. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)