On the micro channel small program development has always wanted to write a relevant article summary and record, the results of procrastination made delayed writing; The weather is good recently, so find a free afternoon to output this article (seems to have nothing to do with the weather 😓), then let’s start!
Note: The default developer of this article has a certain grammatical basis for the development of wechat applets.
Wechat small program summary
In the process of wechat applets development, it is not difficult to find that wechat applets for the convenience of developers to start with a lot of low-level API encapsulation, such as wx.request() for interface request, wx.Switchtab, Wx.Navigateto for route jump and page navigation, etc.. Although it simplifies the development to a certain extent, it is still not enough for the systematic construction of project engineering. Therefore, by comparing my previous vUe-based development experience and my own development habits, I have summarized the following three points for reference:
-
Unified management of global variables and configuration information;
-
2. Encapsulate router guard apis: router.beforeeach () and router.aftereach () of vue-router are really sweet;
-
3. The interface requests further extraction and encapsulation of public information;
-
4, encapsulates the request and response of the interface to intercept API: axios axios. Interceptors. Request. Use () and axios. Interceptors. Response. Use () used are good;
Starting from the above four points, standardized optimization of wechat small program initialization project can greatly improve the development efficiency and project maintenance and management. The benefits of encapsulation are not only in terms of ease of invocation, but also in terms of ease of administration. At the same time, common operations are handled centrally, which greatly reduces complex and repetitive code.
I. Project initialization
Create a wechat applet project and create the following directories and files under the project:
- Config folder: Centrally manages configurable information and variables.
- Errolist. js: The interface reported an error
Error code
Match list file; - GlobalData. Js:
The global variable
Unified management of files (equivalent to VUEX); - Keys. js: configurable system information management file (global constant naming, etc.);
- Errolist. js: The interface reported an error
- Pages folder: applets page file management folder (a subfolder directory for each page);
- Router folder: Routing management file;
- Router.js: small program for wechat
Five routes for navigation
API encapsulation; - Routerconfig. js: The page route name and path match the configuration file;
- Routerfilter. js: Route prefixes
intercept
Encapsulation;
- Router.js: small program for wechat
- Servers file: Interface request service management folder;
- Apis folder: Request request encapsulation management and interface API configuration management folder.
- Request. Js: that’s right
wx.request
thePromise
Encapsulation; - Xxx.js: interface management file of the corresponding module;
- Request. Js: that’s right
- RequestFilter. Js: interface
Request and response interception
Encapsulate files;
- Apis folder: Request request encapsulation management and interface API configuration management folder.
- Everything else is the default initialization file;
Route jump and route guard encapsulation
1. Route forward encapsulation
The official documentation of wechat applets provides developers with 5 apis for routing hops, each with its own special usage:
According to its usage, we encapsulate the routing API as follows: Wechat applets route jump corresponds to push, replace, POP, relaunch, switchTab; Routes correspond to the configuration of the route path in routeConfig. Js. RouterFilter corresponds to the RouterFilter. js file, which processes the logic before routing.
Routeconfig.js (manually added after each new page) :
export const routes =
{
INDEX: "/pages/index/index".TEST: "/pages/test/test",}export default{... routes};Copy the code
RouterFilter. Js:
export default() = > {...// Logical processing before route redirection
}
Copy the code
Router. js (routerFilter handles public operations before a route jump and public operations after a route jump in SUCCESS and FAIL) :
import routes from ".. /router/routerConfig";
import routerFilter from "./routerFilter"
/** * Encapsulation of wx.navigateTo *@param Routing} { path
* @param } {parameter params
* @param } {events events
*/
const push = (path, params, events) = > {
routerFilter()
wx.navigateTo({
url: routes[path] + `? query=The ${JSON.stringify(params)}`.events: events,
success(res) {
console.log(res);
},
fail(err) {
console.log(err); }})}/** * Encapsulation of wx.redirectTo *@param Routing} { path
* @param } {parameter params
*/
const replace = (path, params) = > {
routerFilter()
wx.redirectTo({
url: routes[path] + `? query=The ${JSON.stringify(params)}`.success(res) {
console.log(res);
},
fail(err) {
console.log(err); }})}/** * Encapsulate wx.navigateBack *@param {return level} number
*/
const pop = (number) = > {
routerFilter()
wx.navigateBack({
delta: number,
success(res) {
console.log(res);
},
fail(err) {
console.log(err); }})}/** * Encapsulation of wx.reLaunch *@param Routing} { path
* @param } {parameter params
*/
const relaunch = (path, params) = > {
routerFilter()
wx.reLaunch({
url: routes[path] + `? query=The ${JSON.stringify(params)}`.success(res) {
console.log(res);
},
fail(err) {
console.log(err); }})}/** * Encapsulates tabbar *@param Routing} { 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
}
Copy the code
2. Global registration and use
Globally register the encapsulated routing API in app.js:
import router from "./router/router.js"
// Global registration
wx.router = router
Copy the code
Use in page logic:
// The test page is displayed
gotoTest(){
wx.router.push("TEST")}Copy the code
3. Interface request Promise encapsulation
For the same project, many parameters in wechat apiWx.request () are the same, if directly used, need to copy these repeated parameters again and again, although copy is very simple, but when a parameter changes need to find all interfaces one by one to modify, maintenance is laborious, And it was hard to look at;
Wouldn’t it be nice to wrap wx.request() as a Promise like axios does for a request:
Request. Js:
import formatError from ".. /requestFilter"
const app = getApp()
/** * Interface request encapsulation *@param {request mode} method
* @param {requested URL} url
* @param {data requested to pass} data
*/
const request = (method, url, data) = > {
// Set the request header
constHeader = {···}// Promise encapsulates a layer that is received directly with then and catch when invoked
return new Promise((resolve, reject) = > {
wx.request({
method: method,
url: app.globalData.host + url, // complete host
data: data,
header: header,
success(res) {
// Perform data management and unified logic operations on successfully returned requests... the resolve (res) data)},fail(err) {
wx.showToast({
title: 'Network exception, try again later! '.mask: true.icon: 'none'.duration: 3000})})})}export default request;
Copy the code
The specific use
Take user.js as an example:
import request from "./request";
// Get user openID
export const usrInfos = data= > request("POST"."/user/usrInfos", data);
Copy the code
Index page call:
//index.js
// Get the application instance
const app = getApp()
import { usrInfos } from ".. /.. /servers/apis/user"
Page({
onLoad: function () {
// Get user information
usrInfos({
uid: "xxxx"
})
.then(res= > {
console.log(res)
})
.catch(err= > {
console.log(err)
})
}
})
Copy the code
Request and response interception encapsulation of the interface
Axios axios. Interceptors. Request. Use () and axios. Interceptors. Response. Use () before the corresponding interface request intercept intercept treatment after data processing and response; According to this principle, we also intercept and encapsulate the response of wechat applet, and uniformly manage the output of interface request return error:
request.js
import formatError from ".. /requestFilter"
constThe app = getApp ()...const request = (method, url, data) = >{...return new Promise((resolve, reject) = >{wx. Request ({...success(res) {
// Perform data management and unified logic operations on successfully returned requests
if(res.statusCode === 200) {// The request returned successfully
if(res.data && res.data.code === "SUCCESS") {// The back end processes the interface request successfully and returns data to the interface caller
resolve(res.data) / / then receive
}else{ // The backend pair also requests an error that is considered illogical
formatError(res) // Unified error handling logic
reject(res.data) / / catch}}else{
reject(res.data) / / catch}},fail(err) { // The request failed
wx.showToast({
title: 'Network exception, try again later! '.mask: true.icon: 'none'.duration: 3000})})})}export default request;
Copy the code
requestFilter.js
In requestfilter.js, there are many ways to handle errors. Here’s a simple toast example:
/** * Format the backend error returned by the interface *@param {data successfully returned by the interface} res
*/
const formatError = (err= >{
wx.showToast({
title: err.message,
mask: false.icon: 'none'.duration: 3000})}export default formatError;
Copy the code
Unified handling of error reports requires clear data rules:
- Formulate unified error code management standards;
- Develop unified data return format of interface request for front and back ends;
Global data management
Data management is less important in small projects, but as projects get bigger and more data is available, a good data management solution can effectively avoid bugs, which is why VUex has a strong presence in the VUE ecosystem. Adhering to the principle of reasonable data management, the encapsulated data is firmly encapsulated, and the configuration managed by modules is firmly managed in blocks:
globalData.js
The globalData management of wechat applets is placed in the app.js globalData attribute. When there is too much data or the app.js logic is too complex, it is indeed a good solution to extract the globalData and manage it separately:
export default{...host: "http://www.wawow.xyz/api/test".// The domain name and prefix of the interface requested by the interface
hasConfirm: "" // Confirm instance already exists
currentPage: ""...}Copy the code
keys.js
Keys.js is a custom operation for personal development, which centrally manages some constant names that may be used in the project. It is very convenient to call and modify the maintenance:
export default{...TOKEN: "token".STORAGEITEM: "test"...}Copy the code
Global reference and registration
The introduction of the app. Js:
import router from "./router/router.js"
import keys from "./config/keys"
import globalData from "./config/globalData"
// Global registration
wx.router = router
wx.$KEYS = keys
//app.js
App({
// Listen for applet initialization
onLaunch(options) {
// Get information about the page the applet entered initially
let launchInfos = wx.getLaunchOptionsSync()
// Save the current page route to the global data management
this.globalData.currentPage = launchInfos.path
},
···
// Global data store
globalData: globalData
})
Copy the code
use
In the page code logic can be called by app.globaldata.host, wx.$keys. TOKEN;
Six, summarized
The above mentioned aspects of micro channel small program development are learned and summarized in practice, the implementation of the technical level is actually very easy, but I think the development specification project engineering construction is an important foundation of a project; A good specification can effectively improve development efficiency and unnecessary wrangling between developers! Reasonable project construction can optimize the development logic, improve the legibility of the code logic, reduce the management time of the later project, and give the project greater expansibility.
Welcome to discuss the message, to supplement!