当前位置:网站首页>Wechat applet development experience
Wechat applet development experience
2022-07-06 12:52:00 【Demon Lord】
May Day holiday follows B Station made a mall applet , Write down the ideas and some processes .( Recommend wechat in the whole process Official documents )
Small program development and traditional web Front end development is very similar
Tradition | Wechat applet | |
structure | HTML | WXML |
style | CSS | WXSS |
Logic | Javascript | Javascript |
To configure | nothing | JSON |
What is wechat applet ?
Applet A kind of , English name Wechat Mini Program, It can be used without downloading and installing application , It implements the application “ Within reach ” The dream of , Users can scan or search to open the application .
The advantages of applets
1. Wechat has a huge number ⽤⼾,⽽ And it's sticky ⾼, On wechat ⾥ Developing products is easier to reach ⽤⼾;
2. PUSH ⼴app Or the cost of official account is too low. ⾼.
3. Low development adaptation cost .
4. Easy to ⼩ Scale trial and error , And then iterate quickly .
5. Cross platform .
Register to get APPID Click registration
Developer tools Click to download
Your first applet
New project selection applet project , Select the hard disk path where the code is stored , Fill in the applet's AppID, Give your project a nice name , Check " Not using cloud services " ( Be careful : You need to select an empty directory to create a project ), Click New , You've got your first little program , Click compile on the top menu to preview your first widget in wechat developer tools .
Next, let's preview the effect of this small program .
Compile preview
Click the compile button on the tool , You can see the performance of this applet in the simulator interface on the left side of the tool , You can also click the preview button , Experience your first app on your mobile phone through wechat scanning .
Small program code composition
Different types of files are generated in the project :
.json
SuffixJSON
The configuration file.wxml
SuffixWXML
Template file.wxss
SuffixWXSS
The style file.js
SuffixJS
Script logic file. ├── app.js # Logic file of small program ├── app.json # Applet configuration file ├── app.wxss # Global common style file ├── pages # Each page where the applet is stored │ ├── index # index page │ │ ├── index.js # Page logic │ │ ├── index.json # Configuration page │ │ ├── index.wxml # Page structure │ │ └── index.wxss # Page style sheets │ └── logs # logs page │ ├── logs.js # Page logic │ ├── logs.json # Configuration page │ ├── logs.wxml # Page structure │ └── logs.wxss # Page style sheets ├── project.config.json └── utils └── util.js
JSON To configure
JSON Is a data format , It's not a programming language , In the applet ,JSON Play the role of static configuration .
We can see that there is a... In the root directory of the project app.json
and project.config.json
, In addition to pages/logs
There is another one in the catalog logs.json
.
Applet configuration app.json
app.json
Is the global configuration of the current applet , Including all the page paths of the applet 、 Interface performance 、 Network timeout 、 Bottom tab etc. .QuickStart In the project app.json
The configuration is as follows :
{
"pages":[
"pages/index/index",
"pages/logs/logs"
],
"window":{
"backgroundTextStyle":"light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "Weixin",
"navigationBarTextStyle":"black"
}
}
Let's briefly talk about the meaning of each item of this configuration :
pages
Field —— Used to describe all page paths of the current applet , This is to let wechat clients know which directory your applet page is currently defined in .window
Field —— Define the background color at the top of all pages of the applet , Text color definition, etc .
Tool configuration project.config.json
Usually when you use a tool , They will make some personalized configurations according to their preferences , For example, interface color 、 Compile configuration, etc , When you change to another computer and re install the tools , You have to reconfigure .
With that in mind , The applet developer tool generates a project.config.json
, Any configuration you make on the tool will be written to this file , When you re install tools or change your computer to work , You just load the code package of the same project , The developer tool will automatically help you recover to the personalized configuration when you developed the project , It will include the editor's color 、 A series of options such as automatic compression when uploading code .
Configuration page page.json
there page.json
It's actually used to mean pages/logs In the catalog logs.json
This kind of configuration related to applet pages .
If the style of your entire applet is blue , Then you can go to app.json
The inside states that the top color is blue . This may not be the case , Maybe every page in your applet has different colors to distinguish different functional modules , So we offer page.json
, Let developers define some properties of each page independently , For example, just said the top color 、 Whether to allow drop-down refresh, etc .
JSON grammar
Let's talk about the small program JSON Configuration considerations .
JSON The documents are all wrapped in braces {}, adopt key-value How to express data .JSON Of Key Must be wrapped in a double quotation mark , In practice , To write JSON When , Forget to give Key It's a common mistake to use double quotes for values or single quotes for double quotes .
JSON The value of can only be in the following data formats , Any other format will trigger an error , for example JavaScript Medium undefined.
- Numbers , Contains floating-point numbers and integers
- character string , Need to wrap in double quotes
- Bool value ,true perhaps false
- Array , Need to be wrapped in square brackets []
- object , Need to wrap in braces {}
- Null
The other thing to note is that JSON Cannot use comment in file , An attempt to add a comment will result in an error .
WXML Templates
People who have worked in web programming know , Web programming uses HTML + CSS + JS This combination , among HTML
It is used to describe the structure of the current page ,CSS
Used to describe what a page looks like ,JS
It is usually used to deal with the interaction between the page and the user .
In the same way , There's the same role in applets , among WXML
It's like HTML
Role . open pages/index/index.wxml
, You will see the following :
<view class="container">
<view class="userinfo">
<button wx:if="{
{!hasUserInfo && canIUse}}"> Get head nickname </button>
<block wx:else>
<image src="{
{userInfo.avatarUrl}}" background-size="cover"></image>
<text class="userinfo-nickname">{
{userInfo.nickName}}</text>
</block>
</view>
<view class="usermotto">
<text class="user-motto">{
{motto}}</text>
</view>
</view>
and HTML
Very similar ,WXML
By label 、 Properties and so on . But there are many differences , Let's elaborate one by one :
The label name is a little different
Often write HTML When , The commonly used label is
div
,p
,span
, When writing a page, developers can combine different components according to these basic tags , For example, calendar 、 Pop up window and so on . Change the way of thinking , Since everyone needs these components , Why can't we package these common components , Greatly improve our development efficiency .As can be seen from the example above , Applet
WXML
The label used isview
,button
,text
wait , These tags are the basic capabilities of applet packaging for developers , We also provided maps 、 video 、 Audio and other component capabilities .A few more
wx:if
Such attributes as well as { { }} Such an expressionIn the general development process of web pages , We usually pass
JS
operationDOM
( CorrespondingHTML
The description of the generated tree ), Respond to user behavior by causing some changes in the interface . for example , When a user clicks a button ,JS
Will record some status toJS
Inside the variable , At the same time throughDOM
API ManipulationDOM
The property or behavior of , Then cause some changes in the interface . When the project gets bigger and bigger , Your code will be filled with a lot of interface interaction logic and various state variables of the program , Obviously, this is not a good development model , So there it is MVVM Development model ( for example React, Vue), Advocate the separation of rendering and logic . Simply put, don't letJS
Direct ManipulationDOM
,JS
Just manage the status , Then, a template syntax is used to describe the relationship between state and interface structure .The framework of small programs also uses this idea , If you need to put one
Hello World
The string is displayed on the interface .WXML That's what it says :
<text>{ {msg}}</text>
JS Just manage the status :
this.setData({ msg: "Hello World" })
adopt { { }} The syntax binds a variable to the interface , We call it data binding . Data binding alone is not enough to completely describe the relationship between state and interface , It also needs to be
if
/else
,for
And so on , In the applet , These control capabilities are usedwx:
Start with an attribute to express .
WXSS style
WXSS
have CSS
Most of the features , The applet is WXSS
Some extensions and modifications have also been made .
Added dimension units . Writing
CSS
style , Developers need to consider that the screen of mobile devices will have different width and device pixel ratio , Use some techniques to convert some pixel units .WXSS
Support new units of size at the bottomrpx
, Developers can avoid the hassle of conversion , Just give it to the bottom layer of the applet to convert , Because of the floating-point operation used in conversion , So the result of the calculation will deviate from the expected result a little bit .Provides global and local styles . And the front
app.json
,page.json
The same concept , You can write oneapp.wxss
As a global style , It will work on all pages of the current applet , Partial page stylespage.wxss
Only valid for the current page .Besides
WXSS
Only partialCSS
Selectors
JS Logical interaction
It's not enough for a service to only display the interface , You also need to interact with users : Respond to user clicks 、 Get the user's location and so on . In the applet , We just wrote JS
Script files to handle user actions .
<view>{
{ msg }}</view>
<button bindtap="clickMe"> Click on the I </button>
Click on button
Button time , We want to put the interface on msg
Display as "Hello World"
, So we were button
There's an attribute in it : bindtap
, stay JS It's stated in the document clickMe
Method to respond to this click :
Page({
clickMe: function() {
this.setData({ msg: "Hello World" })
}
})
Applet hosting environment
We call the environment provided by wechat client to applet the host environment . Applets take advantage of the capabilities provided by the host environment , It can complete many functions that ordinary web pages can't .
Render layer and logic layer
First , Let's briefly understand the running environment of the applet . The running environment of the applet is divided into rendering layer and logic layer , among WXML Templates and WXSS Styles work in the render layer ,JS Scripts work at the logical level .
The rendering layer and logic layer of the applet are respectively composed of 2 Thread management : The rendering layer interface uses WebView Rendering ; Logic layer adopts JsCore Thread running JS Script . A small program has multiple interfaces , So there are multiple render layers WebView Threads , The communication between these two threads will be via wechat client ( We will also use Native Wechat client ) Make a transfer , The logic layer sends network requests through Native forward , The communication model of the applet is shown in the figure below .
Programs and pages
Wechat client before opening the applet , Will download the entire applet code package to the local .
And then through app.json
Of pages
Field to know all the page paths of your current applet :
{
"pages":[
"pages/index/index",
"pages/logs/logs"
]
}
This configuration is described in QuickStart The project defines two pages , They are located in pages/index/index
and pages/logs/logs
. And it's written in pages
The first page of the field is the home page of the app ( Open the first page that the applet sees ).
So the wechat client loads the code of the home page , Through the underlying mechanism of the applet , You can render this home page .
After the applet starts , stay app.js
Defined App
Example of onLaunch
Callbacks are executed :
App({
onLaunch: function () {
// After the applet starts Trigger
}
})
There is only one... In the whole applet App example , It's all page sharing , Refer to the documentation for more event callbacks Registration procedure App .
Next, let's take a brief look at how a page of the applet is written .
You can observe that pages/logs/logs
The following actually includes 4 Type of file , Wechat client will first according to logs.json
Configuration generates an interface , The top color and text you can see in this json
It's defined in the file . Then the client will load the page WXML
The structure and WXSS
style . Finally, the client will load logs.js
, You can see logs.js
The general content of is :
Page({
data: { // Data involved in page rendering
logs: []
},
onLoad: function () {
// After rendering the page perform
}
})
Page
It's a page builder , This constructor generates a page . When generating a page , The applet framework will put data
Data and index.wxml
Render the final structure together , So you get what the little program looks like .
After rendering the interface , The page instance will receive a onLoad
The callback , You can handle your logic in this callback .
Components
Applets provide rich basic components for developers , Developers can be like building blocks , Combine various components to form your own small program .
It's like HTML
Of div
, p
Just like the label , In the applet , You just need to WXML
Write the corresponding component tag name to display the component on the interface , for example , You need to display the map on the interface , You just need to write like this :
<map></map>
When using components , You can also pass values to components through properties , So that components can be presented in different states , for example , We hope the longitude and latitude of the center at the beginning of the map is Guangzhou , Then you need to declare the map longitude( Center longitude ) and latitude( Center latitude ) Two attributes :
<map longitude=" Guangzhou longitude " latitude=" Guangzhou latitude "></map>
The internal behavior of components will also be perceived by developers in the form of events , For example, the user clicks a mark on the map , You can js
To write markertap
Function to handle :
<map bindmarkertap="markertap" longitude=" Guangzhou longitude " latitude=" Guangzhou latitude "></map>
Of course you can too style
perhaps class
To control the outer style of the component , So as to adapt to your interface width, height, etc .
API
In order to make it easy for developers to adjust the capabilities provided by wechat , For example, get user information 、 Wechat payment and so on , The applet provides a lot of API For developers to use .
To get the user's geographic location , It only needs :
wx.getLocation({
type: 'wgs84',
success: (res) => {
var latitude = res.latitude // latitude
var longitude = res.longitude // longitude
}
})
Call wechat scanning capability , It only needs :
wx.scanCode({
success: (res) => {
console.log(res)
}
})
It should be noted that : Most of the API The callbacks are asynchronous , You need to deal with the asynchronous problem of code logic .
Applets work together and publish
In large and medium-sized companies , The division of labor is very careful , Generally, employees in different roles will participate in the same applet project at the same time . So , The applet platform designs different permission management, so that the project manager can more efficiently manage the collaborative work of the whole team .
In the past, after we developed the web page , You need to put the code and resources of the web page on the server , Let users access... Through the Internet . In the platform of applet , After the developer completes the development , You need to submit the code package of the applet in the developer tool , And then in Applet background Publish applet , The user can enter the applet through search or other entry .
In this chapter, we will introduce the precautions of team collaboration and the concepts and processes involved before and after the release of the applet .
Working together
If you're just developing small programs by yourself , You can skip this part for now , If you are a team, you need to understand some concepts first .
Most of the time , Multiple people in a team participate in the same applet project at the same time , Each role has different work or permissions , The division of labor of large and medium-sized companies is more careful . In order to more vividly express the relationship between different roles of the team and the management of permissions , We use a virtual project member organization structure to describe how to cooperate to complete the release of a small program , The organizational relationship is shown in the figure 5-1 Shown .
chart 5-1 Virtual applet project team
Project management members are responsible for coordinating the progress and risks of the whole project 、 Control the rhythm of the release of the applet , Demand from product team , The design team discusses with the product and abstracts the requirements , Design visual flow and graphics , Output design scheme . The development team is based on the design scheme , Write program code , After the code is written , The product group and Design Group experience the overall process of the applet , The test group writes test cases and performs various boundary tests on the applet . The general membership and workflow of the project are shown in the figure 5-2 Shown .
chart 5-2 The process from raising requirements to releasing applets
Applet member management
Applet member management includes the management of applet project members and experience members .
Members of the project : Indicates participation in applet development 、 Members of the operation , Can log in small program management background , Including operators 、 Developers and data analysts . Administrators can “ Member management ” Add 、 Delete project members , And set the roles of project members .
Experience members : Represents the members participating in the applet in-house test experience , You can use the experience applet , But not a member of the project . Administrators and project members can add 、 Delete experience members .
Different project members have different permissions , So as to ensure the safety and order of small program development .
jurisdiction | The operator | developer | Data Analyst |
---|---|---|---|
Developer rights | √ | ||
Experience authority | √ | √ | √ |
Sign in | √ | √ | √ |
Data analysis | √ | ||
Wechat payment | √ | ||
Extension | √ | ||
Development management | √ | ||
Development and setup | √ | ||
Temporarily Out of Service | √ | ||
The official account No. | √ | ||
Tencent cloud management | √ | ||
Widget plugin | √ | ||
Game operation management | √ |
Description of each authority function
- Developer rights : You can use applet developer tools and development version applets for development
- Experience authority : You can use the experience applet
- Sign in : Can log in small program management background , Administrator confirmation is not required
- Data analysis : Use the applet statistics module function to view applet data
- Wechat payment : Wechat payment using applet ( Virtual payment ) modular
- Extension : Use applet traffic master 、 Advertiser module
- Development management : Applets submitted for review 、 Release 、 Back off
- Development and setup : Set applet server domain name 、 Message push and scan ordinary link QR code to open applet
- Pause service settings : Pause applet online service
- The official account No. : Official account that can be tied to small programs.
- Widget plugin : It can be used for applet plug-in development, management and setting
- Game operation management : You can use small games to manage the material management in the background 、 Game circle management and other functions
Need to pay attention to , The project manager controls the release of the entire applet 、 Back off 、 Off the shelf and other sensitive operations , The authority of sensitive operations should not be assigned to irrelevant personnel
The version of the applet
General software development process , Developers write code self-test development version program , Until the program reaches a stable and experiential state , Developers will give this experience version to product managers and testers for experience testing , Finally, the program is repaired Bug Post release for official use by external users . The version of applet designs the concept of applet version according to this process , As shown in the table 5-3 Shown .
surface 5-3 The version of the applet
jurisdiction | explain |
---|---|
Development version | Use developer tools , You can upload the code to the development version . The development version only keeps the latest uploaded code of each person . Click submit for review , The code can be submitted for review . The development version can be deleted , It does not affect the code of the online version and the version under review . |
Experience version | You can select a development version as the experience version , And choose an experience version . |
Version under review | There can only be one copy of the code under review . The audit results can be published online , You can also resubmit for approval directly , Overwrite the original approved version . |
Online version | The version of the code used by all users online , The version code is updated after the new version code is released . |
Considering that the project is a collaborative development mode , A small program may be developed by multiple developers at the same time , Often developers need to go to the mobile phone for real machine experience after coding on the applet developer tool , Therefore, each developer has its own corresponding development version . Because the version under development is unstable , Developers will modify the code to cover the development version at any time , In order to let test and product managers have a complete and stable version to experience testing , The applet platform allows one of the development versions to be set as an experience version , Therefore, it is suggested to assign a special development role in the project development stage , Used to upload stable code for experience testing , And set the development version he uploaded to the experience version .
Published online
A small program usually goes through preview -> Upload code -> Submit audit -> Release and other steps .
preview
Use developer tools to preview applets , Help developers check the real performance of applets on mobile clients .
Click the preview button on the operation bar at the top of the developer tool , The developer tool will automatically package the current project , And upload the applet code to the wechat server , After success, a QR code will be displayed on the interface . Use the wechat scanning code of the current applet developer to see the real performance of the applet on the mobile client .
Upload code
Different from Preview , Upload code is used to submit experience or audit .
Click the upload button on the operation bar at the top of the developer tool , Fill in the version number and project remarks , It should be noted that , The version number and project notes here are for the convenience of the administrator to check the version , Developers can fill in these two fields according to their actual requirements .
After uploading successfully , Sign in Applet management background - Development management - Development version You can find the version just submitted for upload .
You can set this version Experience version Or is it Submit audit
Submit audit
In order to ensure the quality of small programs , And comply with relevant specifications , The release of small programs needs to be audited .
After uploading the applet code in the developer tool , Sign in Applet management background - Development management - Development version Find the version submitted for upload .
In the list of development versions , Click on Submit audit Follow the page prompts , Fill in the relevant information , That is, you can submit the applet for review .
It should be noted that , Ask the developer to strictly test the version , And then submit it for review , Too many audits failed , It may affect the follow-up time .
Release
After approval , The administrator will receive the notification that the applet has passed the audit in the wechat , Log in at this time Applet management background - Development management - The approved version can be seen in the approved version .
Click post , You can publish the applet . The applet provides two publishing modes : Full release and phased release . Full volume publishing refers to when you click publish , All users will use the latest release version when accessing the applet . Phased release refers to controlling some users to use the latest release version in different time periods , Phased publishing is also called gray publishing . Generally speaking , Ordinary small programs can be released in full , When more and more functions are carried by applets , When the number of users is increasing , Using phased release is a very good way to control risk .
Finally, remember that the interface written on the back end is a perfect wechat applet !
边栏推荐
- Unity3D,阿里云服务器,平台配置
- (课设第一套)1-5 317号子任务 (100 分)(Dijkstra:重边自环)
- (5) Introduction to R language bioinformatics -- ORF and sequence analysis
- [算法] 剑指offer2 golang 面试题2:二进制加法
- Unity scene jump and exit
- [leetcode19] delete the penultimate node in the linked list
- 闇の連鎖(LCA+树上差分)
- Expected value (EV)
- Idea problem record
- 使用rtknavi进行RT-PPP测试
猜你喜欢
Affichage du changement de valeur du Buff de gain de l'interface graphique de défaillance
[算法] 剑指offer2 golang 面试题13:二维子矩阵的数字之和
编辑距离(多源BFS)
idea中导包方法
In 2020, the average salary of IT industry exceeded 170000, ranking first
Naive Bayesian theory derivation
FGUI工程打包发布&导入Unity&将UI显示出来的方式
[untitled]
Compilation principle: preprocessing of source program and design and implementation of lexical analysis program (including code)
基本Dos命令
随机推荐
基本Dos命令
Unity scene jump and exit
(课设第一套)1-5 317号子任务 (100 分)(Dijkstra:重边自环)
The service robots that have been hyped by capital and the Winter Olympics are not just a flash in the pan
[算法] 剑指offer2 golang 面试题6:排序数组中的两个数字之和
[algorithm] sword finger offer2 golang interview question 8: the shortest subarray with a sum greater than or equal to K
雇佣收银员【差分约束】
MySQL error warning: a long semaphore wait
最短Hamilton路径 (状压DP)
Combination of fairygui check box and progress bar
Itext 7 生成PDF总结
Fabrication of fairygui simple Backpack
1041 be unique (20 points (s)) (hash: find the first number that occurs once)
How to improve the deletion speed of sequential class containers?
[algorithme] swordfinger offer2 golang question d'entrevue 2: addition binaire
On March 15, the official version of go 1.18 was released to learn about the latest features and usage
FairyGUI增益BUFF數值改變的顯示
GNSS定位精度指标计算
(the first set of course design) sub task 1-5 317 (100 points) (dijkstra: heavy edge self loop)
[算法] 剑指offer2 golang 面试题4:只出现一次的数字