Little Lee's Mobile Development Growth Story -- Big Talk About Small Programs
act asTraditional websites
Students of front-end developers who are new toapplet
There will be manyperplexity
Why there is no div, what is view, why there is no ajax, why is it a callback, how to use applet developer tool for preview, what is the use of APPID, how to install npm packages but still have to build, what is the tabBar, how is the syntax similar to vue but some parts are different, how is the use of @import different from the use of css ...
This post introduces small programs through WeChat Small Programs (released earlier and more influential) to help youA quick look at the applet
, and resolve the above confusion. Main Introduction:
- Small programs and
node
discrepancy - Small programs and
vue
grammatical difference - The applet communication model and
operating mechanism
- Tripartite mini-programs
development process
- How to create a new project, what are the global and local configurations
- applet
basic grammar
:wxsl、wxss、js(wxs) - applet
Promise-ization of APIs
- appliance
life cycle
and page lifecycle - Applet components and custom components
- applet
Routing and State
managerial - What is subcontracting and what does it do
contexts
Although Li knows some react, vue, and js, he has done less mobile development and almostCan't do small programs.
Development.
The next stage is toMobile Development
The company's main focus is on the development of mobile applications, including H5, applets, in-house mobile frameworks, debugging tools, TS, and so on.
How to get up to speed on this part of the job, and after three minutes of thinking about it, decide on a general direction to strengthen:
- applet: There are many small programs developed
- js Basics: code should be written elegantly, e.g. a lot of if is not a good habit; don't feel rusty when you see someone else's Promise, you can also see if there is a problem with someone else's deconstructed writing style
- react: The project's tech stack uses react
- Strengthening TS: Many codes have TS, otherwise they are unreadable and modifications to the code do not pass compilation
- Mobile Development ProcessFamiliarity with the company's mobile development process, such as emulators, cloud-based real machines, physical machines, and the company's packet grabbing tools
- Mobile PlayFor example, if you call jsAPI (getLocation), you need to enable "system geolocation, system authorize host (alipay/small program) geolocation privilege, host give small program geolocation privilege" at the same time, otherwise it may pop up the popup box of "geolocation privilege request". "pop-up box; hoverball play; half-screen display; full-screen display page (i.e., the webview extends to the status bar)
Getting to know the applet
Applet VS Website
Small Programs Similar Websites
, just the website opens in the browser, while the applet opens through the applet platform (WeChat, Alipay).
both sidesresemblance
:
- Cross-platform: WeChat applet opens in WeChat, Alipay applet opens in Alipay; website opens in browser
- No download and installation required
- Real-time updates: once released, users will automatically get the latest version
both sidespoint of difference
:
- Running environment: the host of the applet is the applet platform, such as WeChat, Alipay; the website runs in the browser;
- Functions and permissions: small programs, because they are embedded in super applications (WeChat, Alipay), can call some native functions, such as payment, geolocation, camera, and some of the functions require user authorization; websites are limited by the API provided by browsers, and the authorization will be more limited in general;
- Experience and Performance: Small programs are closer to native apps in terms of experience and performance, with faster response and smoother UI.
- Ecology and traffic: with the platform ecology of super applications, it is easy to acquire users. For example, WeChat applets can spread quickly through social channels such as WeChat groups and circles of friends; websites are optimized through search engine optimization (SEO), advertisements, and promotion may be difficult relative to applets
- Development languages and tools: use specific frameworks and toolsets, e.g. WeChat applets use WXML, WXSS, JS; websites use standard HTML, CSS, JS and various front-end frameworks and libraries (React, Vue)
- Development mode: the website is a browser + code editor; WeChat small program: apply for a small program development account, install small program developer tools, create and configure small program projects
- Code hosting: after the local development of the website is submitted to the code hosting platform (github), it will be deployed from the hosting platform to the actual running server; after the small program code is written and debugged locally, it will be directly uploaded to the corresponding small program platform, which involves the use of the official developer tools provided to upload the code, the platform audit, and the release of the audited program; the small program platform is responsible for the hosting and version control of the code.
WeChat Small Program VS Vue
Some people say that applets are much simpler than Vue. Let's compare the similarities and differences between the two and we'll see thatApplets are syntactically similar to vue in many ways
。
common ground
:
- Component development: WeChat applets use wxml to define the component structure, wxss to define the style, js to define the logic, json for configuration; Vue uses .vue for single-file component development.
- Data binding: microsoft applet through
{{}}
Data binding, similar to template syntax - Event handling: WeChat applets use event binding such as bingdtap or catchtap; vue uses v-on (or @) for event binding
- Conditional and list rendering: applets use wx:if and wx:for directives; vue uses v-if and v-for directives
point of difference
:
- Running environment: WeChat applets run in WeChat's container environment and can only be used in WeChat, relying on WeChat's APIs and platform; vue runs in the browser and in.
- File structure: WeChat applet, each component consists of 4 files (wxml, wxss, js, json); vue in a .vue file
- Style handling: WeChat applets use wxss for definition, similar to CSS; vue uses standard CSS
- Framework features: WeChat applet: provides some APIs specific to the WeChat environment, such as access to WeChat payment; Vue focuses on the UI layer and provides a rich ecosystem
- Ecosystem and extensions: WeChat applets, rich APIs provided by WeChat officials, community contributed component libraries and development tools; Vue has a strong ecosystem, including a large number of third-party plug-ins, component libraries and development tools
host environment
cell phonemicrosoft
is the host environment for microsoft applets.Alipay, online payment platform
It's the host environment for the Alipay applet
With the ability provided by the host environment, the applet can accomplish many functions that cannot be done by ordinary web pages, such as: WeChat login, WeChat payment, WeChat code scanning, geo-location...
The capabilities provided by the applet through the host environment include:communications model
、operating mechanism
、subassemblies
cap (a poem)API
communications model
The body of the applet communication contains:rendering layer
cap (a poem)logic layer
- wxml (html-like) and wxss (css-like) work in the rendering layer
- js scripts work at the logical level
The communication model in the applet is in two parts:
- Rendering layer and logic layer communication: forwarding by WeChat client
- Communication between the logical layer and the third-party server: forwarding by the WeChat client
operating mechanism
appletpriming process
:
- Download the applet code locallyWhen a user opens or updates a small program for the first time, the WeChat client will download the code package of the small program from a remote server. This process may vary depending on the network conditions and the size of the code package, and the WeChat platform will optimize and compress the code package to speed up the download.
- Parsing Global Configuration Files: After the download is complete, the WeChat client will first parse the file, which contains the global configuration information of the applet, such as the page path, window performance, network timeout time, bottom tab, etc.. These configurations determine the basic framework and presentation of the small program.
- fulfillment, Small Program Entry File: Next, the WeChat client will execute the file, which is the logic layer entry of the small program. In it, the App function will be called to create the instance of the applet, and you can define the global data and methods in this function, and perform some initialization operations, such as registering the global lifecycle callback functions (e.g. onLaunch, onShow, onHide, etc.).
- Rendering the applet home page: Based on the path to the home page configured in , the WeChat client will load the .wxml (structure), .wxss (style) and .js (logic) files of the home page and start rendering the home page of the applet. The logic layer creates the page instance through the Page function and executes the page's lifecycle functions, such as onLoad, to perform data initialization, network requests, and other operations. Subsequently, the rendering layer renders the page content based on the data provided by the logic layer.
- Applet startup complete: When the home page is rendered and presented to the user, it marks the end of the startup process of the applet, at which time the user can start interacting with the applet. At the same time, different pages of the applet can jump between pages through page routing, and the logic layer and the rendering layer continue to update data and redraw the interface according to the user's operation.
Tip: The above is a cold start, and for applets that have already been opened, re-entering may be a hot start. For example, the code download may be skipped
The page rendering process
:
- Load the .json configuration file for the parsed page: When a page needs to be rendered, the WeChat applet framework first loads the .json configuration file corresponding to that page. This file defines page-level configuration information such as the page's window style, navigation bar style, etc. These configurations affect the appearance and behavior of the page.
- Loading the .wxml and .wxss styles of a page: Immediately after that, the framework loads the page's structure file, .wxml, which defines the structure and layout of the page, similar to HTML, and the style file, .wxss, which controls the style of the page's elements, similar to CSS. Together, these two files determine the appearance of the page.
- Execute the page's .js file, call Page() to create the page instance: After that, the framework executes the page's logic file .js. In this file, the page instance is created by calling the Page function and you can define the page's initialization data, lifecycle functions (e.g., onLoad, onShow, onHide, etc.), event handling functions, and so on in it. The initialization data and logical processing of the page are done in this stage.
- Page rendering complete: When the structure, styles and data of the page are ready, the rendering engine of the WeChat app renders the page based on the .wxml and .wxss and the data in the page instance. This process includes parsing the WXML template, applying WXSS styles, binding data to the template, and finally generating the user-visible interface. Once the page is rendered, the user can see and start interacting with the page.
API
The applet officially divides APIs into three categories:
-
Event Listening API
: Starts with on and listens for certain events. For example (callback) (there is no windown in the applet) listens for the window size to change. -
Synchronization API
: Anything ending in Sync is a synchronization API, which is obtained directly through a function that throws an exception if executed incorrectly. For example, ('key', 'value') writes data to the local cache. - Asynchronous API: similar to $.ajax, need to receive the result of the call through success, fail, cpmplete, such as initiating a request for network data, receive the result of the call through success.
Small program development process
Small program development processUnlike traditional websites
。
Traditional web development: vscode to write code, browser to preview results, git commit to code.
The steps of small program development are roughly as follows (in terms of WeChat small program)trilateral
(Development as an example):
- Apply for an applet account and get the AppId (the unique identifier of the applet you want to create)
- Create a project through the applet developer tool
- Preview the effect by compiling with the applet developer tool
- Uploading code to the WeChat platform via the applet developer tool
- Select a development version as an experience
- Experience Completion Application Release
- Post to WeChat platform
TipOne-party development usually refers to the development by the owner of the applet, which is also the official development; three-party development, which refers to the third-party developers to provide functions or services for the applet.
Applet account and APPID
The main reason for registering a small program account is to get an APPID.
APPID
It is a small program unique identification, used to identify and distinguish different small programs on WeChat.During the registration process, you need to fill in some basic information, such as the name of the small program, the introduction of the small program, the category of the small program and so on. After completing these, WeChat will generate an APPID for you, which will be used to develop, publish and operate various operations of the small program, including the configuration of development tools, etc.
The general process is as follows:
- Click to register: go to the official website of WeChat (
/cgi-bin/wx
), click on "Register" - Registration of small programs: contains account information (email, password ...) , mailbox activation, information registration (country of registration, type of subject - individual: ID name, ID card, cell phone, SMS)
After registering, you can login to the background management interface of the app, and you can find the APPID in the "Development" navigation.
Small program development tools
How do you preview the effect of a small program without using a specific tool?Browsers don't recognize applets
WeChat Developer Tool provides the following features:
- Quickly create an applet project
- Code Viewing and Editing
- Applets for debugging, previewing
- Small program release
Find the stable version of the download and installation success, you will see a QR code on the desktop, with their own WeChat sweep, log in to open the "WeChat Developer Tools".
Create project: you can specify the directory where the project is located, whether to choose cloud development for the backend service, and whether the language is javascript or TypeScript.
Main interface of the applet tool
In five parts:
- Menu bar: e.g. Help (with "Developer Documentation"), Settings, Programs, Tools (with).
Build npm
(plug-ins) - Toolbar: Simulator, Editor, Debugger,
compiling
、real-time debugging (of a computer)
- Simulator: simulates WeChat (at the bottom there are: page path,
Page parameters
) - Code editing area
- Debugging area:
console
、Network、Storage
Customized compilation modes
Through the applet tool.normal compilation
Will start from the small program home page, and usually we modify the logic of a page, save and want to see the effect immediately, instead of switching from the home page several times to the page. This is, we can use "custom compilation conditions".
Click "Add Compile Mode" under "Normal Compile", select the page you want to start, you can also pass the parameter, and create a new page. Next time, you can select this page to compile.
Multiple compiled pages can be created for a single page, such as a referenced, un-referenced...
cooperative work
Small programs are not usually done by one person.
WeChat applet member management (trilateral
) Reflected in the administrator's management of applet program members and experience members
- Project members: participate in the development, operation, can log in the background of the small program, the administrator can add, delete members, and set the role of members
- Experience members: participate in the small program internal testing experience, can use the experience version of the small program, does not belong to the project members, administrators and project members can add, delete experience members
Developer permissions are available:
- Developer rights
- Experiencer Privileges
- Login access: Login to the background of the applet without administrator confirmation
- Development settings: set the small program server domain name, message push and scan the ordinary QR code to open the small program
Tip: The reason for these roles is that the development process for applets is different from website development in that the code for applets is managed by the applet platform.
Applet version
The small program release process is roughly as follows: upload the code to the development version, iterate the development version several times, generate the experience version according to the development version, submit for review after passing the verification, and release after passing the review.
-
development version
: Using the developer tools, code can be uploaded to the development version. The development version keeps only the latest copy of the uploaded code for each person. Click Submit for Review to submit the code for review. Deletion of the development version does not affect the online version or the version under review. -
trial version
: Select a development version as an experimental version -
Version under review
: Only one copy of the code can be under review. You can post it online when you have a review result, or you can just resubmit it for review, overwriting the original review version -
online version
: the version of the code used by all users online
Tip: Both WeChat applets and Alipay applets provide multi-version development and management features. Experience versions can only be generated based on one of the development versions at the same time.
Promotional and operational data
Once published, it needs to be promoted
Promotion can be based on WeChat codes and small program codes.
Advantages of small program codes:
- More recognizable in style
- -More clarity in establishing a small program brand image
The applet can be viewed through the backendOperational Data
You can also use the "small program data assistant" (WeChat search) to view the data related to the published small program: access analysis, real-time peer, user profiles ...
Small programs can also use third-party burying tools, such as: Friends of the Friends, Shenzhe data...
Applet support and limitations for npm packages
WeChat applets support NPM packages, butThere aren't a lot of Npm packages available for applets.
。
Here are some limitations and caveats:
- API limitation: npm packages that depend on built-in libraries, built-in browser objects, C++ plugins are not supported.
- Package Size Limit: There is a limit on the package size of WeChat applets, a single package can not exceed 2 MB, and the total volume can not exceed 20 MB. therefore, you need to pay attention to the size of NPM packages to avoid exceeding the limit.
- Build Tools: NPM packages need to be built and processed through the WeChat developer tools, make sure the "Build NPM" feature is enabled in the developer tools.
New projects and configurations
Basic structure of the project
Create a microsoft applet project thatdirectory structure
Below:
- pages: all the pages of the applet
- utils: the module that holds the utilities
- : applet entry files
- utils: the global configuration file of the applet. Contains the paths of all pages of the applet, the appearance of the window, the interface performance (the background color of all pages, the text color, the version of the style used by the applet components), and the bottom tabs.
- : Project configuration file. Record our personalized configuration of the applet development tool, such as project name, applet account ID, compilation-related configuration (ES6 to ES5, automatic compression and obfuscation when uploading code, automatic style completion when uploading code)
- : Configure whether the small program and its pages are allowed to be indexed by WeChat. WeChat is now open to search within the small program, similar to the SEO of the web page.
Applet officials recommend that all applet pages be placed in thepages
directory in a separate folder:
- pages
- index
- Page Scripts
- Page structure
- Page styles
- Configuration of the current page, such as the appearance of the window
- pageb
-pageb
pageb - -
pageb - -
- -
Tip: There are 4 types of small programsjson configuration file
(specific roles will be described later)
- in the root directory of the project
- in the root directory of the project
- in the root directory of the project
- json in each page folder
New applet page
Add a new page storage path in ->pages, ctrl+s to save it, and the tool willautomation
Create the corresponding page file.
{
pages: [
"pages/index/index",
"pages/pageb/pageb",
+ "pages/pageb/pagec"
]
}
Modify the project home page
simplyalign
->pages array of page paths in thesequences
, the applet will render the page that comes first, as the project home page.
global configuration
in the root directory of the applet is the applet global configuration file.
Common Configurations:
- pages Records the current applet all the pages of the storage path
- window Global settings for the appearance of the applet window
- tabBar Set the tabBar effect at the bottom of the applet.
- style Whether to enable the new version of the component style
Example:
{
"pages": [
"pages/index/index",
"pages/logs/logs"
],
"window": {
"navigationBarTitleText": "Sample applet",
"navigationBarBackgroundColor": "#ffffff",
"navigationBarTextStyle": "black",
"backgroundColor": "#eeeeee",
"backgroundTextStyle": "light",
"enablePullDownRefresh": true,
"onReachBottomDistance": 50
},
"tabBar": {
"color": "#7A7E83",
"selectedColor": "#3cc51f",
"borderStyle": "black",
"backgroundColor": "#ffffff",
"list": [
{
"pagePath": "pages/index/index",
"text": "home page (of a website)",
"iconPath": "images/icon_home.png",
"selectedIconPath": "images/icon_home_active.png"
},
{
"pagePath": "pages/logs/logs",
"text": "log (computing)",
"iconPath": "images/icon_logs.png",
"selectedIconPath": "images/icon_logs_active.png"
}
]
},
"style": "v2"
}
computer operating system window
Applet window components (top to bottom):
- navigationBar
Navigation bar area
: Includes time, power, tweet title -
background
Background area, invisible by default, only visible in dropdowns -
Page body area
The layout in wxml is used to display the layout of the
Common configuration items for windown nodes:
- navigationBarTitleText
Navigation bar title
text string - navigationBarBackgroundColor navigation bar background color default #000000, type HexColor
- navigationBarTextStyle navigation bar color (title, battery, etc.) only support black/white, default white
- backgroundColor Window background color default #ffffff, type H3xColor
- backgroundTextStyle The style of the dropdown loading, only support dark/light, default dark.
- enablePullDownRefresh Whether to enable pull down refresh globally. Default is false, when enabled, it will be applied to every page of the app.
- onReachBottomDistance The distance from the bottom of the page when the page is triggered at the bottom of the page, in px, default is 50, if there is no special need, it is not recommended to change it.
Tip:drop-down refresh
The usual practice is to turn it on individually in the page, rather than globally here. Once pull down refresh is turned on, if you want to realize the refresh, you still have to handle the down refresh logic in the onPullDownRefresh method, which will be called when the user triggers the pull down refresh operation.
classifier for sums of money
: The emulator can't restore 100% of the real machine. For example, in the emulator, after 3 seconds, the dropdown will be closed automatically, while in the real machine, it will not be closed automatically.
tabBar
The tabBar in the applet isnavigation component
. Characteristics have:
- Location: Usually located at the bottom of the applet interface.
- Icons and text: Each tab can contain icons and text.
- Selected State: You can configure the icon and text color for selected and unselected states.
- Page Mapping: Each tab corresponds to a page path, clicking the tab will switch to the corresponding page.
The following is a typical MediumtabBar Configuration Example
:
{
"tabBar": {
"color": "#999999",
"selectedColor": "#1c1c1b",
"backgroundColor": "#ffffff",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/home/index",
"text": "home page (of a website)",
"iconPath": "/images/icon_home.png",
"selectedIconPath": "/images/icon_home_active.png"
},
{
"pagePath": "pages/search/index",
"text": "look for sth.",
"iconPath": "/images/icon_search.png",
"selectedIconPath": "/images/icon_search_active.png"
},
{
"pagePath": "pages/profile/index",
"text": "my",
"iconPath": "/images/icon_profile.png",
"selectedIconPath": "/images/icon_profile_active.png"
}
]
}
}
classifier for sums of money
: The tabBar can only be configured with a minimum of 2 and a maximum of 5. When rendering the top tabBar, theDo not show icon
, only text is displayed. It says that the pages in the tabBar should be placed in front of the pages, otherwise they won't be displayed.
tabBar has 6 components:
- color, the color of the text on the tab
- selectedColor, the color of the tab text when it is selected.
- backgroundColor, tabBar background color
- borderStyle, tabBar border color
- iconPath, the path of the image when it is unchecked.
- selectedIconPath, the path of the selected icon.
tabBar node configuration item:
- position, default bottom, configurable top
- borderStyle, default black, only black/white is supported.
- color, hexColor type
- selectedColor, hexColor type
- backgroundColor, hexColor type
- list, Array, Required.
Minimum 2, maximum 5
Each tab entry configures options:
- pagePath, required, the path of the page, the page must be predefined in pages.
- text, required, the text to be displayed on the tab.
- iconPath, the path of the icon when it is unchecked; the icon will not be shown when the position is top.
- selectedIconPath, the path of the selected icon; the icon will not be shown when the position is top.
Page Configuration
In the applet, global configuration and page configuration can beDefining the appearance and behavior of a page
. When global and page configurations conflict, the proximity principle is indeed followed, and the end result is usually the page configuration. This means that the page-specific configuration overrides the global configuration. This ensures that the page customization works.
Commonly used configuration items in page configuration:
- navigationBarTitleText The navigation bar title.
- navigationBarBackgroundColor navigation bar background color
- navigationBarTextStyle navigation bar text color
- backgroundColor The background color of the page.
- backgroundTextStyle The style of the dropdown loading.
- enablePullDownRefresh Whether to enable pull down refresh globally.
- onReachBottomDistance The distance to the bottom of the page when the page pull-up bottom-touch time is triggered.
- disableScroll
- List of custom components used on the usingComponents page
Basic Applet Syntax
wxml
The wxml in WeChat applet is similar to html in webpage. axml in Alipay applet.
The difference between wxml and html
:
- The tag names are different (e.g. view instead of div):
- HTML: div、span、img、a
- wxml: view、text、image、navigator
- Attribute nodes are different
<a href="">Baidu</a>
<navigator url="">Baidu</navigator>
- Provides vue-like template syntax: data binding, list rendering, conditional rendering
data binding
Define data in data to be used in wxml. Example:
Page({
data: {
name: 'ZhangSan',
name: 'ZhangSan', age: 18, url: '...
url: 'http://... .png', randomNum: () * 10, randomNum: ()
randomNum: () * 10, }
}
})
Using the Mustache syntax ({{}}
) Just wrap the variables:
<view>{{ name }}</view>
<view>{{ randomNum > 5 ? 'greater than 5': 'less than or equal to 5' }}</view> <view> {{ name }}</view> {{ randomNum > 5 ?
Unlike vue's v-bind, the applet's dynamically bound properties are written directly on the label (It's just written differently. Just memorize it.
), for example:
<image src="{{ url }}"></image>
Tip: The data is available in the AppData tab of the applet development tool console.
conditional rendering
Comparison of conditional rendering in applets and vue:
- Syntax difference: microsoft applets use wx:if, hidden, block wx:if, v-if, v-show in vue.
- wx:if is similar to v-if and is true conditional rendering
- hidden is similar to v-hsow in that it is controlled by css and the element is always present.
- A block is similar to a template in that it controls the display and hiding of multiple components at once, and none of them are rendered as actual dom elements.
Usage: Use wx:if, wx:elif, wx:else tags in wxml, define variables in data, use variables in wx:if.
<view>
<view wx:if="{{ age > 18 }}">
You're an adult.
</view> <view wx:if="{{ age > 18 }}" >
<view wx:elif="{{ age < 18 }}"> You are underage
</view> <view wx:elif="{{ age < 18 }}"> You are underage
<view wx:else>
You are underage
</view> <view wx:else> You are very young.
</view>.
list rendering
Comparison of list rendering in applets and vue:
- Syntax difference: microsoft applets use wx:for, wx:key, vue uses v-for and :key
- Both emphasize the importance of having a unique key for each item in the list rendering
- vue provides richer functionality in list rendering
- wx:for is similar to v-for in that it traverses the array and renders it as a list
Usage: Use wx:for tag in wxml, define array in data, use array in wx:for.
The default index of the current loop item is index, and the current loop item is item.
<view class="container">
<block wx:for="{{items}}" wx:key="index">
<view>
<text>{{index}}: {{item}}</text>
</view>
</block>
</view>
Page({
data: {
items: ['Item 1', 'Item 2', 'Item 3']
}
});
wx:for-item and wx:for-index are used to customize variable names, making the code clearer and more readable.
<view class="container">
<block wx:for="{{items}}" wx:for-item="user" wx:for-index="idx" wx:key="id">
<view>
<text>Index: {{idx}}</text>
<text>ID: {{}}</text>
<text>Name: {{}}</text>
</view>
</block>
</view>
Page({
data: {
items: [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
]
}
});
classifier for sums of money
: The key of the applet, which is directly an attribute in the loop item and doesn't require the{{}}
. If it's vue, you have to go through the loop items to find the
<template v-for="item in items" :key="">
wxss
Styles for applets, similar to css for web pages.
wxss vs css
wxss has most of the specifics of css, and wxss also extends and modifies css to accommodate applet development.
The difference between wxss and css:
- additional
rpx
(responsive pixel) size unit- Implementing responsive layout in css requires manual pixel conversion (commonly rem). For example, if the designer provides a 750 draft, we might equate 1rem to 75, and 75 in the draft is 1rem
- wxss in the underlying support for the new size unit rpx, in different screens will automatically be converted, the same is 750 manuscript, 75 size directly written as 75rpx that can be.
- Provides global and local styles
- WeChat applets: in the project root directory will work on all applet pages; local page .wxss styles will only work on the current page
- CSS is global in the web, unless you use CSS modularization tools.
- File type: microsoft applet is .wxss
- Media query: WeChat applet does not support traditional CSS media query, such as
@media
- css animation and overdrive: microsoft applets support some css animation and overdrive, but there are some limitations
- wxss supports only some common css properties and selectors: .class and #id, element, concatenated and descendant selectors, pseudo-class selectors such as ::after and ::before.
- flex layout: flex in WeChat applets is mostly consistent with css, but there are subtle differences in the specific performance
- Introduction style: WeChat small program through
@import
Introduces other .wxss, does not support external css in the form of @import url().
rpx
The rpx principle is very simple, taking the screens of all devices from the width of the750 aliquots
- In a 375 device, 1rpx equals 0.5px
- On a 1500 device, 1rpx equals 2px.
Tip: rem and rpx In implementing a responsive layout, the main concern is width adaptation. Height needs to be handled on its own, such as expanding isometrically, or limiting the maximum height.
The width of the iphone screen is 375px (logical pixels) with 750 pixels (physical pixels), 1 logical pixel is equal to 2 physical pixels, equals 750rpx. then:
- 750rpx = 375px = 750 physical pixels
- 1rpx = 0.5px = 1 physical pixel
Development example: according to the design, some requirements are 1:1, some are 1:2, 100px widthA 200px box, converted to rpx is 200rpx.400rpx。
@import
The relative path of the outreach style to be imported after @import, terminated by ;. Example:
@import "";
.box{
}
Use class instead of className.
Tip: WeChat applets support the use of less, though some configuration is required.
Global and local styles
The styles defined in are global styles that apply to every page.
Styles defined in a page's .wxss are localized and apply only to the current page.
classifier for sums of money
: when local styles conflict with global styles, it's the same as in css: whichever has the highest weight is used, and if the weights are the same, the proximity principle is used (local styles are taken)
Tip: Place the mouse over the selector in the applet tool, there will be a selection prompt, e.g. Selector Specificity:(0, 1, 0)
js
Tip: The js in the applet is divided into 3 main categories
- : the applet entry file, by calling the App() function to start the entire applet
- Page.js: the entry file for the page, which creates and runs the page by calling the Page() function.
- Common.js: common function module file, used to encapsulate public functions or attributes for use on the page
wxs
The role of wxs in a WeChat app is similar to the role of the(machine) filter
(vue3 has deprecated the filter)
The wxs and javascript in applets are two languages, the difference is:
- wxs runs in the view layer, js runs in the logic layer
- wxs isolation. Cannot call functions defined in js, cannot call applet APIs
- wxs was originally designed to improve data processing performance, especially in scenarios closely related to interface rendering, and to reduce communication with the logic layer.
Tip: In ios, wxs within applets is 2~20 times blockier than js; no difference on Android.
The syntax of wxs is based on JavaScript, which means that if you are familiar with JavaScript, learning wxs will be relatively easy:
- wxs has its own data types: number, string, boolean, array, object...
- wxs doesn't support es6+-like syntax, doesn't support let, const, deconstruct assignment, arrow function; supports var, function, es5 syntax
- wxs follows the commonjs specification: module objects, require() functions, objects
- wxs can be written in
<wxs>
tag, just as js is written in the<script>
In wxs, the module attribute must be provided to specify the current wxs module name.
Outbound wxs usage (src must be a relative path):
<!-- -->
<wxs module="utils" src="../../utils/"/>
<view>
<text>{{(new Date())}}</text>
</view>
//
= {
formatDate: function(date) {
var year = ();
var month = () + 1;
var day = ();
return [year, month, day].map().join('-');
},
formatNumber: function(n) {
n = ();
return n[1] ? n : '0' + n;
}
};
Data requests
Small program in the network data, in security considerations, small program official data interface to do the following restrictions:
Only https type interfaces can be requested
- The domain name of the interface must be added to the trust list
If you want to request the interface under /domain name in your own WeChat small program. Configuration steps: Login to the WeChat small program background - > development - > development settings - > server domain name - > modify the REQUEST legal domain name. Attention:
- Domain name only supports https
- The domain name cannot be an ip address or localhost
- Domain name must be ICP filed
- Server domain name can be applied for modification up to 5 times in a month
Tip: If the back-end only provides http protocol interface, in order not to delay the development progress, you can temporarily enable the "development environment does not verify the request domain name, TLS version and HTTPS certificate" in the WeChat developer tool to skip the request legitimate domain name verification, which can only be used in the development and debugging stage.
get and post requests
In a WeChat app, you can use the method to initiate HTTP GET and POST requests. This method provides a simple way to interact with the server for data:
See example:
({
url: '/data',
method: 'GET',
data: {
key1: 'value1',
key2: 'value2'
},
header: {
'content-type': 'application/json'
},
success: function(res) {
},
fail: function(err) {
}
});
({
url: '/submit',
method: 'POST',
data: {
key1: 'value1',
key2: 'value2'
},
header: {
'content-type': 'application/json'
},
success: function(res) {
},
fail: function(err) {
}
});
Applets and cross domains
Applets don't have the usual cross-domain issues, but they still essentially involve a few
. But for front-end development, there is no need to deal with cross-domains.
Cross-Origin Resource Sharing (CORS for short) refers to a document or script under one domain name that tries to request a resource under another domain name, but the request is blocked due to the browser's Same-origin policy restrictions. Same-origin" means that the protocol, domain name, and port number are identical. Same-origin policy is a security measure designed to prevent a malicious website from reading sensitive data from another website through scripts.
The essence of a cross-domain is a Same-origin policy implemented by the browser for security reasons.
The body of the applet is not the browser, but the applet platform, so there are no regular cross-domain issues.
Because the small program needs to be configured with a trusted domain name, in fact, there is also a certain degree of security, the service side of the small program will also involve the configuration of CORS
Applets and Ajax
The Ajax core relies on the XMLHttpRequest object in the browser, and the host environment of the applet is the WeChat client, so theThe applet is not called "initiating an ajax request", it's called "initiating a web request".
WeChat small program does not directly use the term ajax, but provides a similar asynchronous HTTP request capability, mainly through the interface to complete the Get or Post request, this process is very similar to Ajax, are asynchronous to obtain data and update the interface without blocking the page. So small programs do not say "ajax", but in fact have the ability to obtain data asynchronously!
Similar to ajax, but with different operating environments and implementation mechanisms.
See example:
({
url: '/data',
method: 'GET',
data: {
key1: 'value1',
key2: 'value2'
}, // Request Parameters
header: {
'content-type': 'application/json'
},
success: function(res) {
},
fail: function(err) {
}
});
can be used with async/await and:
- Wrap a Promise function that uses the
const request = (options) => {
return new Promise((resolve, reject) => {
({
...options,
success: res => resolve(res),
fail: err => reject(err)
});
});
};
- Then use it in async/await:
Page({
async onLoad() {
try {
const response = await request({
url: '/api/data',
method: 'GET'
});
('Data:', );
} catch (err) {
('Error:', err);
}
}
});
Promise-ization of the applet API
When developing WeChat apps, many of the native APIs are based on thecallback function
which can be inconvenient in modern JavaScript programming. To better handle asynchronous operations, we can convert these APIs in the form of callback functions intoPromise
formality
One type of manual encapsulation
One is to use a library (e.g. miniprogram-api-promise). Example:
Install it, build it, configure it in your project and use it:
//
import wxp from 'miniprogram-api-promise';
App({
onLaunch() {
// replacing all wx function (math.) promise ... -ize
();
}
});
Used in a page or component:
// pages/index/
Page({
data: {},
async onLoad() {
try {
const response = await ({
url: '/data',
method: 'GET',
});
();
} catch (error) {
(error);
}
}
});
life cycle
There are two types of life cycles for applets:
-
Application Life Cycle
: Applet from start->run->destroy -
Page Lifecycle
: Load-> Render-> Destroy for each page in the applet
Pages have a small lifecycle scope and applications have a large lifecycle scope:
Applet start -> Lifecycle of page A -> Lifecycle of page B -> Lifecycle of page C -> Applet end
Application Life Cycle
The application life cycle function needs to be written in:
App({
onLaunch: function(opts) {},
onShow: function(opts){},
hoHide: function(){},
})
- onLaunch: executed immediately after the applet starts, only triggered once globally. Suitable for some initialization settings, such as login, global variable initialization, etc.
- onShow: Triggered when the applet starts or goes from background to foreground display. You can perform data request, restore interface state and other operations here.
- onHide: Triggered when the applet enters the background from the foreground. You can clean up temporary data here, pause the timer, etc. to save resources.
- onError: Capture abnormal errors of the applet, including script errors, API call errors, etc. It is very useful for monitoring the running status of the applet.
- onUnhandledRejection (optional): catches unhandled Promise rejection errors, a newer API for enhanced error handling.
TipWeChat developer tools have an option "cut background", you can simulate cut to the background!
Page Lifecycle
Each applet page also has its own independent life cycle, which is mainly used to control the process of loading, rendering, displaying, hiding and unloading the page. The main life cycle includes:
- onLoad: Triggered when the page loads (
A page is called only once
). Suitable for initializing page data, getting page parameters, etc. - onShow: Triggered when the page is shown/cut to the foreground. You can set the page data here, respond to the parameters passed in the previous page, and so on.
- onReady: triggered when the initial rendering of the page is complete (
A page is called only once
). Some DOM manipulation can be done at this point (although it is generally recommended to use setData to change the interface). - onHide: triggered when page hide/cut background. You can save the state of the page here, stop the timer, and so on.
- onUnload: Triggered when the page is unloaded. Good for doing some cleanup work, such as canceling network requests, removing event listeners, etc.
- onPullDownRefresh: Triggered when the page is pulled down and refreshed, you need to enablePullDownRefresh in the page configuration.
- onReachBottom: triggered when the page reaches the bottom, used to load more data in paging.
- onPageScroll: triggered when the page is scrolled, can be used to monitor the page scroll position.
- onShareAppMessage: triggered when user clicks the share button in the page, used to customize the sharing content
Tip: The backend goes to the frontend and executes the global onShow first, then the onShow of the page.
drop-down refresh
Enable dropdown refresh have global open dropdown and local open dropdown, the actual development, it is recommended to use local open down, that is, for the need of the page to open the dropdown separately.
Here's a bit about the realization:
- Enable localized page dropdowns
{
"enablePullDownRefresh": true
}
- In the page to implement the dropdown refresh logic, pay attention to call stopPullDownRefresh, otherwise the real machine in the dropdown effect has been displayed, will not actively disappear.
Page({
onPullDownRefresh: function() {
// Write your data reload or update logic here
('Refreshing...') ;
// Simulate an asynchronous data loading process, which in reality may be initiating a network request for new data
setTimeout(() => {
// Stop the dropdown refresh animation when the data is loaded.
();
('Refresh complete'); }, 1000); // Delay time.
}, 1000); // The delay time is for example only and should be adjusted according to your data loading time.
}, // The delay time is only an example and should be adjusted according to your data loading time.
// Other lifecycle functions and methods for the page...
})
pull-up and hit bottom
As mentioned earlier, the default configuration is 50px from the bottom of the trigger, no special requirements do not have to change the
Now to implement the pull-up touch bottom logic, just code it in onReachBottom:
Page({
data: {
itemList: [], // initial data list
page: 1, // the current page number, used for loading pages
hasMore: true // whether there is more data
}, // the initial list of data.
onReachBottom: function() {
// Triggered when the user reaches the bottom of the page.
if () {
(); } else {
} else {
({
title: 'No more data',
icon: 'none'
});
}
},
behaviors
Applet behaviors and vuemixins
Similarities. The similarities are there:
- All of them can define the properties and data of the component.
- Both can define lifecycle functions (lifetimes in WeChat applets, lifecycle hooks like created in Vue, etc.)
There are some problems with mixins:
- Naming Conflicts: Naming conflicts can occur when multiple mixins and the component itself define properties or methods with the same name; Vue uses a prioritization mechanism to decide which to use, but this can lead to unexpected behavior.
- Source Unknown: When looking at a component, it's not clear which properties and methods are derived from mixins, which can make code difficult to understand and maintain. This is especially problematic in large projects where multiple mixins are used on top of each other.
- Coupling: mixins put together shared logic that can be highly dependent on the data structures and other logic of the component itself, leading to a high degree of coupling that makes mixins difficult to reuse and test.
Vue 3's Composition API can replace mixins in many cases and addresses some of the shortcomings of mixins, such as naming conflicts and unclear code organization.
The difference between applet hehaviors and mixins in vue:
- Merge strategies for properties and data: Vue provides more detailed merge strategies (e.g., array merging and object overriding), while the behaviors of WeChat applets mainly override properties
- Multiple Inheritance: The behaviors of WeChat applets support multiple inheritance, i.e., a component can use multiple behaviors; Vue's mixins also support multiple mixins, but Vue's strategy is more complex and flexible when it comes to conflict resolution
event
event binding
Events are communication from the rendering layer to the logic layer.
: Events take the actions generated by the user in the rendering layer and feed them back to the logic layer for processing.
Commonly used events in applets:
-
tap
The binding method is bindtap or bind:tap, the finger will leave immediately after touching, similar to the click event in html. - input, the binding method is bindinput or bind:input, the input event of the text box
- change, bind as bindchange or bind:change, triggered on state change
In WeChat applets, it is recommended to use tap instead of click in traditional html, because applets are specially designed with tap events to handle user clicks in order to optimize the mobile touch experience. Relative to click, there are several advantages:
- Optimization for mobile devices: click has a delay of 300ms on mobile devices, this is to differentiate between single click and double click operations. Tap has no such delay
- Better touch experience: tap is designed for touch screen, which is more in line with the user's operating habits on mobile devices.
See example:
Page({
data: {
message: 'Button not yet clicked'
}, { data: { message: 'Button not yet clicked'
// Methods aren't written in methods like vue, they're on the same level as data.
handleTap: function (e) {
({
message: 'The button was clicked!
});
({
title: 'You clicked on the button',
icon: 'none'
}); ({ title: 'You clicked the button', icon: 'none')
}
});
<view class="container">
<button bindtap="handleTap">Click on me</button>
<view class="message">{{message}}</view>
</view>
In addition to the tap event, the applet also provides some common touch events: longpress, touchstart, touchemove, touchend, touchcancel, and so on.
Tip: Other events in the applet are
Event Type | event | clarification |
---|---|---|
touch event | touchstart | Finger touching action starts |
touchmove | fingerprint | |
touchend | End of finger touch action | |
touchcancel | Finger touch action is interrupted, e.g. caller alert | |
tap | Leave immediately after touching with your fingers. | |
longpress | More than 350ms before leaving after finger touching | |
longtap | Finger touch over 350ms before leaving (alias) | |
form event | submit | Form Submission |
reset | Form Reset | |
input | Triggered by input box entry | |
focus | Triggered when the input box gets focus | |
blur | Triggered when the input box loses focus | |
media incident | play | start playing |
pause | pause (media player) | |
ended | End of playback | |
timeupdate | Playback progress update | |
error | playback error | |
waiting | Loading | |
Picture Events | load | Triggered when image loading is complete |
error | Triggered on image loading error | |
rolling event | scroll | Triggered on scrolling |
scrolltoupper | Triggered when scrolling to the top/left | |
scrolltolower | Triggered when scrolling to the bottom/right | |
Open capability event | contact | Triggered when a user clicks the customer service button |
getuserinfo | Get user information event | |
getphonenumber | Get user's cell phone number event |
event object
When an event callback is triggered, there is an event object event with detailed properties:
- type, string, event type. For example, tap, its type is tap.
- target, Object, a collection of values for some properties of the component that triggers the time (
in common usage
) - detail, Object, other properties (additional information) in the event object (
in common usage
) - currentTarget, Object, a collection of property values for the component that currently triggers the event.
- touches, Array, touch event, an array of touch point information (how many fingers) currently residing in the screen
- changedTouches, Array, touch events, array of currently changed touch point information
- timeStamp, Integer, the number of milliseconds between the opening of the page and the triggering of the event.
TipThe difference between target and currentTarget is similar to that between target and currentTarget in the web. target is the source of the event that triggered the change, and currentTarget is the component to which the current event is bound. For example, if you click on a button in a view, it's the button, not the view.
<view bind:tap="callback">
<button>btn</button>
</view>
event references
Applet event passing is different from vue
。
You can write it like this in Vue:<button @click="handleClick(123)">Button 1</button>
However, the applet will treat the bindtap attribute value uniformly as an event name, which is equivalent to calling the handleClick(123) event handler.
WeChat small program: viadata-*
property to pass parameters, use (or target).dataset to get the parameters. See the example:
<view class="container">
<button data- data-name="button1" bindtap="handleTap">Button 1</button>
<button data- data-name="button2" bindtap="handleTap">Button 2</button>
</view>
Page({
handleTap: function(event) {
const { id, name } = ; // Get multiple parameters
('Button clicked:', id, name);
}
});
data synchronization
In the WeChat applet. is the primary method used to update data on a page. The view is automatically updated when the data changes. It can be used to modify the data in the Page object and reflect the changes in the data to the interface.
<!-- -->
<view class="container">
<text>numerical value: {{count}}</text>
<button bindtap="incrementCount">rise</button>
<button bindtap="decrementCount">minimize</button>
<input placeholder="input" bindinput="handleInput"/>
<text>input: {{inputValue}}</text>
</view>
//
Page({
data: {
count: 0,
inputValue: ''
},
// rise计数
incrementCount: function () {
({
count: + 1
});
},
// minimize计数
decrementCount: function () {
({
count: - 1
});
},
// Handling Input Events
handleInput: function (e) {
({
inputValue:
});
}
});
Tip:
- In Vue you usually modify the data directly, and for some cases you may need to use this.$set, but in vue3 it's easier to automatically detect and listen for responsive attribute additions and deletions due to the switch to a proxy responsive system.
- The applet's setData is very similar to useState in react. Merge states are merged, not replaced. See example.
Page({
data: {
count: 0,
inputValue: ''
},
incrementCount: function () {
({
count: + 1
});
},
handleInput: function (e) {
({
inputValue:
});
}
});
Synchronization of textboxes and data
For synchronization of textboxes and data, applets and vue implement similar principles.
Bidirectional binding is possible in vue via v-model, but theThe essence of v-model
is an attribute of value and the @input event
<input type="text" v-model="message" placeholder="Enter text"/>
maybe
<input type="text" :value="message" @input="updateMessage" placeholder="Enter text"/>
new Vue({
el: '#app',
data: {
message: ''
},
methods: {
updateMessage(event) {
= ;
}
}
});
With the WeChat applet it's like this:
<input type="text" value="{{inputValue}}" bindinput="handleInput" placeholder="Enter text"/>
Page({
data: {
inputValue: '',
errorMsg: ''
},
handleInput: function(event) {
const value = ;
let errorMsg = '';
if ( < 3) {
errorMsg = 'Input must be at least 3 characters long';
}
({
inputValue: value,
errorMsg: errorMsg
});
}
});
Applet Components
The components in the applet are also provided by the host environment and developers can build beautiful pages based on the components. The component categories of applets are:
- view container
- staple
- form component
- navigation component
- media component
- Map Components
- canvas component
- open capabilities
- Accessibility
Tip: Comparison of commonly used components of WeChat Small Program vs Alipay Small Program. Feels almost the same
Function/Category | WeChat Small Program Components | Alipay Small Program Components | note |
---|---|---|---|
view container | view |
view |
Basic View Container |
scroll-view |
scroll-view |
Scrollable view container | |
swiper |
swiper |
Slider View Container | |
movable-view |
movable-view |
Movable View Container | |
cover-view |
cover-view |
View containers overlaying native components | |
list |
List View Container | ||
staple | text |
text |
text label |
icon |
icon |
icon component | |
rich-text |
rich-text |
Rich Text Component | |
progress |
progress |
progress bar | |
form component | form |
form |
Forms for data collection |
input |
input |
single-line input box | |
textarea |
textarea |
multi-line input box | |
checkbox |
checkbox |
checkbox | |
radio |
radio |
radio button | |
switch |
switch |
switch selector | |
slider |
slider |
slide selector | |
picker |
picker |
picker | |
picker-view |
picker-view |
Scroll selector for embedded pages | |
label |
label |
tag for the description of the form control | |
navigation component | navigator |
navigator |
Page navigation |
media component | image |
image |
Picture Components |
video |
video |
video component | |
audio |
audio |
audio component | |
camera |
camera |
camera assembly | |
live-player |
live-player |
Real-time audio and video playback components | |
live-pusher |
live-pusher |
Real-time Audio and Video Push Streaming Components | |
Map Components | map |
map |
Map Components |
canvas component | canvas |
canvas |
Canvas component for drawing graphics |
open capabilities | open-data |
contact-button |
WeChat Open Data Component and Alipay Customer Service Button |
web-view |
web-view |
Embedded web content | |
ad |
ad |
advertising component | |
official-account |
lifestyle |
WeChat Public Component and Alipay Life Component | |
login |
button |
Login button (used in different scenarios) | |
pay-button |
button |
Payment buttons (used in different scenarios) | |
Accessibility | aria-role |
aria-role |
Accessible Roles |
aria-label |
aria-label |
Accessibility Labeling |
Common View Container Components
- view, common view area, similar to div in html, is a block-level element, commonly used to achieve page layout
- scroll-view, scrollable view area
- swiper and swiper-item, rotogram container component and rotogram item component
ask
: Why not create a view instead of a div?echo
: WeChat applets choose to use custom components such as view instead of native HTML tags such as div for several reasons:
- Framework design: architecture and features for adapting the applet.
- Performance optimization: improve rendering performance and user experience on mobile.
- Consistency and compatibility: Ensure consistent performance across platforms and devices.
- Better support for applet features: deep integration with applet lifecycle, event system and style management.
- Convenient management and maintenance: Provide perfect component system and API, simplify the development and maintenance work.
- Security: Avoid security problems caused by direct operation of the DOM.
- Suitable for mobile development: better adapted to mobile development and user experience needs.
By using the view component, WeChat applets are able to better control and optimize the performance of the application, providing a more efficient and consistent development and user experience.
ask
: Why create a separate scroll-view for scrolling when you have a view?echo
: While the view component already provides basic container functionality, the scroll-view component has the following significant advantages as a specialized scroll container:
- Designed for scrolling: provides a rich set of features and configuration options for easy control of scrolling behavior.
- Smooth scrolling and performance optimization: optimized to provide a better scrolling experience.
- Additional feature support: support for elastic scrolling, scrollbar hiding and other common mobile features.
- Composability and reusability: makes code more modular, readable and maintainable.
- Event listening and processing: rich event mechanism, easy to handle scrolling-related logic.
- Dynamic control of scrolling position: control scrolling position by attributes, support animation effects.
- Avoid style conflicts: Ensure independence and stability of scrolling areas.
In short, the introduction of scroll-view component in WeChat applets is to provide more powerful and optimized scrolling functionality to improve user experience and development efficiency.
ask
: Can't you merge a scroll-view into a view?echo
: While it is theoretically possible to merge the functionality of scroll-view into the view component, in practice it introduces many complexities and technical challenges. WeChat applets choose to implement scroll-view and view separately in order to:
- Keeping components with a single responsibility simplifies development and maintenance.
- Optimize performance for a more efficient scrolling experience.
- Provides rich feature and event support for enhanced flexibility.
- Avoid style and layout conflicts and ensure backward compatibility.
Separate implementations increase the cost of learning and use, but in the long run, they can better meet the needs of developers and users, while keeping the code simple and efficient. Therefore, it is a well-considered design choice for WeChat applets to separate scroll-view.
staple
text
: The selectable attribute can only be used with text, not when it is placed in a view.
rich-tex
t: HTML strings can be rendered into corresponding UI structures through its nodes attribute node.
Other Common Components
-
button
: button component, rich in functionality than button buttons in html (main color, big button small button, warning button ...) The open-type attribute allows you to call various functions provided by WeChat (customer service, forwarding, getting user information). -
image
The image component has a default width of about 300px and a height of about 240px. mode attributes can be used to specify the cropping and scaling of the image, aspectFill is similar to cover, and aspectFit is similar to contain, the differences of which you need to taste. -
navigator
: navigation component, similar to the a tag in html, used for page jumping
Custom Components
The applet developer tool also provides a convenient way to create a component by right clicking on "New Component".
Local and Global Components
Components are categorized from the way they are referenced:
-
local reference
: the component can only be used in the currently referenced page -
global reference
: Components are available for every applet page
- Example of a localized reference:
components/
my-component/
{
"usingComponents": {
"my-component": "/components/my-component/my-component"
}
}
<view>
<my-component text="Welcome to My Component"></my-component>
</view>
//
{
"component": true
}
- Example of a global reference:
components/
my-global-component/
Global reference configuration in
{
"pages": [
"pages/index/index",
"pages/logs/logs"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "WeChat",
"navigationBarTextStyle": "black"
},
"usingComponents": {
"my-global-component": "/components/my-global-component/my-global-component"
}
}
Difference between pages and components
In applets, pages and components have many similarities in the way they are developed and deconstructed and used, but they have different uses and characteristics
characterization | Page | Component |
---|---|---|
functionality | Separate view of user interactions | Reusable functional modules or UI elements |
Component documents |
.wxml , .wxss , .js , .json
|
.wxml , .wxss , .js (calls to Component() functions, events need to be defined in methods), the.json (Required)"component": true ) |
life cycle |
onLoad , onShow , onReady , onHide , onUnload
|
created , attached , ready , moved , detached
|
Routing and navigation | Support for routing and navigation APIs | Routing and navigation are not supported |
Combination and nesting | Cannot be nested in other pages | Can be nested within pages or other components |
reusability | Usually used independently | High, can be referenced in multiple pages |
Component Style Isolation
In the WeChat applet, the style of the component isDefault isolation
of the component. This means that component styles do not affect external pages or other components, and external styles do not affect component internals. This style isolation mechanism helps to increase component independence and reusability
If you want the outside world to affect the component, you can also modify it by setting `"styleIsolation". There are three modes of style isolation for WeChat applets:
- isolated (default): completely isolated, the style of the component will not affect the outside, and the style of the outside will not affect the inside of the component.
- apply-shared: component styles do not affect the outside, but external global styles can affect the inside of the component.
- shared: component styles and external styles affect each other.
Tip: it says that only class selectors will have style isolation effects, id selectors, attribute selectors, and label selectors will not be affected by style isolation
Data, Methods and Properties
data, methods, and properties in the component, see the example:
Component({
properties: {
max: {
type: Number,
value: 10
}
},
data: {
name: 'pjl'
},
methods: {
handleFn() {
// true
( === );
// utilization setData modifications properties (be) worth
({max: + 1})
}
}
})
Tip: It says that the properties attribute and the data data usage in the applet are the same.readable and writable
data-listening
WeChat small program in theobservers
and watch are similar in that they are used to listen and respond to changes in data. However, watch in WeChat provides more options and flexibility for more complex listening needs. WeChat app observers are simpler and more straightforward.
Grammar:
Compoment({
observers: {
'fieldA, fieldB': function(new value for fieldA, new value for fieldB) {
}
}
})
- Listening to multiple data
observers: {
'countA, countB': function(newCountA, newCountB) {
(`CountA has changed to: ${newCountA}, CountB has changed to: ${newCountB}`);
({
sum: newCountA + newCountB
});
}
)
- Listening to multiple properties in an object
observers: {
'obj.v1, obj.v2': function(newFirstElement, newSecondElement) {
(`First element has changed to: ${newFirstElement}, Second element has changed to: ${newSecondElement}`);
}
}
- Listen to all properties in the object
observers: {
'obj.**': function(newObj) {
}
data-only field
WeChat applets havedata-only field
Its main role:
- Reduced data transfer: When using the setData method, all non-plain data fields are serialized and sent to the view layer. If some data is only used in the logic layer and does not need to be rendered to the view, it can be marked as a pure data field to avoid unnecessary transfers, thus improving performance
- State Management: Pure data fields can be used to store some temporary state or calculation results inside the component that do not need to be rendered into the view. For example, caching some calculation results or maintaining some internal state.
- Code maintainability: Marking pure data fields can help developers more clearly distinguish between data that needs to be rendered and data that is only used for logical processing. This helps improve code readability and maintainability.
In options, use thepureDataPattern
. See example:
Component({
// A list of properties for the component
properties: {
initialValue: {
type: Number, value: 0
value: 0
}
},
// Initial data for the component
data: {
displayResult: 0, // Initial data for the component.
__internalCache: 0 // Pure data field, not passed to the view layer.
}, // The initial data for the component.
// Define the match pattern for pure data objects
options: {
pureDataPattern: /^__/
}, // Define the match pattern for pure data objects.
Component Life Cycle
- created (common): triggered when the component instance is created, at this time the component's attribute values, data, etc. have not yet been initialized, and data binding operations cannot be performed (i.e., the setData method cannot be used).
- attached (commonly used): triggered when the component instance enters the page node tree, it can access the attribute values and data, suitable for data binding and initialization work at this stage. It is suitable for data binding and initialization at this stage. It is usually used to initialize data and listen to certain events.
- ready: the layout of the component is complete, that is, the rendering of the view layer has been completed, at this time you can operate on the DOM structure of the component.
- moved: the component instance is moved to another position in the node tree
- detached (common): triggered when the component instance is removed from the page node tree.
It is appropriate to do cleanup work at this stage, such as canceling event listeners, clearing timers, etc., to prevent memory leaks. - error: executed whenever a component method throws an error
For applet components, the lifecycle can be defined directly in the Component constructor level 1 parameter, or it can be written in the lifetimes field (the recommended way, with a higher priority)
Component({
// low priority
error(err) {
},
lifetimes: {
error(err) {
}
}
}).
Component lifecycle on the page
Sometimes, custom component behavior depends on changes in the state of the page, and the lifecycle of the page on which the component resides has to be used. For example, you want to regenerate a number whenever the page's show declaration cycle is triggered.
There are 3 life cycles for the page on which the component resides:
- show: triggered when the page where the component is located is displayed.
- hide: triggered when the page where the component is located is hidden
- resize: triggered when the size of the page where the component is located changes.
Example:
Component({
pageLifetimes: {
show() {
('Component in page show');
// Logic executed when the page is shown
}
}
}).
slots
Similar to vue, there are no scope slots.
Available in single and multiple slots
Component Communications
Component communication in WeChat applets is similar to that in vue, where the parent passes to the child with attributes and the child passes to the parent with events.
Tip: WeChat applets also have parent components that get component instances via () (which should be used sparingly)
Example of passing data from a child component to a parent component:
// subassembly
Component({
methods: {
incrementCount() {
// Triggering custom events,pass on data
('countChange', { count: + 1 });
}
}
});
<view class="my-component">
<button bindtap="incrementCount">Increment</button>
</view>
// parent component
<view class="container">
<my-component bind:countChange="handleCountChange"></my-component>
</view>
Page({
handleCountChange(e) {
// Get the data passed by the subcomponent
const newCount = ;
}
});
WeChat applet installation vant weapp
vant weapp is a set of applet UI component libraries.
Applets that use npm packages are a little different than traditional websites. For example:
- Installation and references: traditional website npm packages will be installed in the node_modules directory; applet developer tools will process the packages in node_modules and put them in the miniprogram_npm directory, when referencing the npm packages, you need to use the miniprogram_npm path, e.g.: "miniprogram_ npm/@vant/weapp/button/index".
- Build: The mini-program requires an additional "Build NPM" operation in WeChat Developer Tools to build the NPM package from node_modules to the miniprogram_npm directory.
- Packet Size Limit: Traditional websites do not have strict limitations on packet size.
WeChat applet to install vant weapp, approximate steps (see vant official website for details):
- Install via npm
- Building npm packages
- modifications
Tip: Miniprograms are special in that every package you install has to be built before you can use it. It is recommended to remove the miniprogram_npm package before building, otherwise it is easy to build failure and other problems!
Routing
Navigation is all about jumping from page to page, and the browser has a<a>
、
vue's single page has theProgrammed Navigation
cap (a poem)Command Line Navigation
, there is also programmatic navigation and command line navigation in microsoft applets
Small programs and single page apps
Let's start with the traditional one-page application:
- Individual HTML pages
- Front-end Routing
- No Refresh Experience
- Front-end and back-end separation
WeChat applets have a similar user experience and some of the technical implementations of single-page apps in a way, but theIt is not a single page application by strict technical definition
。
WeChat small program uses a multi-page framework, each page exists independently. Switching pages will be consistent with the native, and you can do the effect of sliding.
The applet is similar to the single page:
- No Refresh Experience
- Client-side routing: page navigation via client-side APIs
- Front-end and back-end separation
Differences between small programs and single pages:
- Page Independence: Each applet page is independent, with its own file and lifecycle. Traditional apa, on the other hand, dynamically renders and updates content within a single HTML file
- Page loading: applet page switch will load the corresponding file
vue routing vs applet routing
Programmatic and imperative navigation in vue, like this:
this.$({ path: '/some/path', query: { key: 'value' } });
<router-link :to="{ name: 'routeName', params: { userId: 123 } }">Go to User</router-link>
Command navigation in WeChat applets is mainly done through the page's WXML file in the<navigator>
component implementation, similar to the HTML<a>
Tags.
<navigator url="/pages/somePath/somePath">Go to Some Path</navigator>
<navigator url="/pages/tabPage/tabPage" open-type="switchTab">Go to Tab Page</navigator>
Programmatic navigation in WeChat apps is implemented through methods such as , , and . These methods allow developers to perform page jumps in JavaScript code
// keep the current page, jump to a page within the app
({
url: '/pages/somePath/somePath'
});
// Close the current page and go to a page within the app
({
url: '/pages/somePath/somePath'
});
// Jump to the tabBar page and close all other non-tabBar pages.
({
url: '/pages/tabPage/tabPage'
}); // Jump to the tabBar page and close all other non-tabBar pages.
// Close all pages and open to a page within the app
({
url: '/pages/somePath/somePath'
});
comparative analysis
Programmed Navigation:
- Vue Router: navigation via methods like this.$, supports multiple navigation methods (path, name, params, query).
- WeChat small program: navigation through , and other methods, feature-rich, but need to specify a specific URL.
Command navigation:
- Vue Router: via
<router-link>
The components are navigated, semantically strong, structured and easy to read. - WeChat small program: via
<navigator>
component for navigation, with similar functionality to the<router-link>
The first is the Vue route, but it doesn't have the route naming and parameter passing capabilities of Vue, so it needs to be navigated via a URL.
Parameter Passing:
- Vue Router: supports passing parameters via params and query, very flexible.
- WeChat small program: parameters need to be spliced in the URL, not intuitive, parameter passing is relatively complex.
Applicable Scenarios:
- Vue Router: for complex single page applications (SPA) that require powerful route management features and flexible parameter passing.
- WeChat mini-programs: suitable for mini-program development, focusing on simplicity and fast navigation, in line with the mini-program design philosophy.
The comparison shows that Vue Router is much better at managing complex navigation in single page applicationslarge
, while the navigation design of WeChat applets is morepithy
and fast, in line with the need for rapid development of small programs
- Programmatic navigation: Vue Router and WeChat applets both provide powerful programmatic navigation, the former through this.$ and other methods, the latter through methods such as etc. Vue Router is more flexible, more convenient parameter passing; WeChat applets programmatic navigation is more simple, you need to specify a specific URL.
- Command navigation: Vue Router usage
<router-link>
, WeChat small program use<navigator>
Vue Router. Both are similar in functionality and are used to declaratively define navigation structures, but Vue Router provides more powerful route naming and parameter passing capabilities.
Declarative navigation
- Navigate to
tabBar page
: url must start with /; open-type means jump type, must be switchTab. see example:
<navigator url="/pages/page1/page1" open-type="switchTab"> navigate to page1</navigator>
- Navigate to non
tabBar page
The :url must start with /; the open-type indicates the jump mode, which must be navigate (can be omitted). See the example:
<navigator url="/pages/page1/page1" open-type="navigate"> navigate to page1</navigator>
- Back navigation, such as back to previous page or multi-level page: open-type must be navigateBack, means back navigation; delta must be a number (default is 1, can be omitted), means back level. See the example:
<navigator open-type="navigateBack" delta="1"> Return to previous page </navigator>
Programmed Navigation
- Navigate to the tabBar page: call (Object obj). obj has the following attributes: url (required, no parameters after the path), success, fail, complete.
({
url: '/pages/tabBar/home/home',
success: function(res) {
// success callback
},
fail: function(err) {
// failed pullback
}
});
- Navigate to a non-tabBar page: call (Object obj). obj has the following properties: url (required, path can be followed by parameters), success, fail, complete.
({
url: '/pages/page1/page1',
success: function(res) {
// Success callback
}, fail: function(err) { // success callback
fail: function(err) {
// Failure callback
}
}).
- Backward navigation: call (Object obj). obj has the following attributes: delta (default is 1, can be omitted), success, fail, complete.
({
delta: 1,
success: function(res) {
// Success callback
}, fail: function(res) { // Success callback.
fail.
Navigational Passing Parameters
- Declarative navigational passing of parameters: written directly after the
<navigator url="/pages/page1/page1?name=pjl&age=18"> navigate to page1</navigator>
- Programmatic Navigation Passing Parameters
({
url: '/pages/detail/detail?itemId=123&itemName=ExampleItem'
});
New page to receive parameters:
Page({
onLoad: function(options) {
// The options object contains the passed parameters
(); // Output: 123
(); // Output: ExampleItem
}
}).
Status Management
Global data shares are: vuex, mobx, Redux, etc.
The applet can be used in themobx
Manage applet status. Approximate steps:
- Install MobX and MobX's WeChat applet support libraries, mobx-miniprogram and mobx-miniprogram-bindings.
- Building npm packages
- Create a Mobx store: Create a store folder in the project root folder, and then create a file in it that defines your MobX store
// store/
import { observable, action } from 'mobx-miniprogram';
export const store = observable({
// Defining the state
count: 0,
// Defining Calculation Properties
get doubleCount() {
return * 2;
},
// Defining Actions
increment: action(function() {
+= 1;
}),
decrement: action(function() {
-= 1;
})
});
-
Inject the Store into the applet
-
Binding pages with MobX: Use the mobx-miniprogram-bindings library to bind the MobX store in your pages.
// pages/index/
import { createStoreBindings } from 'mobx-miniprogram-bindings';
import { store } from '../../store';
Page({
// initialization Store Bindings
onLoad() {
= createStoreBindings(this, {
store,
fields: ['count', 'doubleCount'],
actions: ['increment', 'decrement']
});
},
// destroy (by melting or burning) Store Bindings
onUnload() {
();
}
});
It is often recommended that each page has its own Store
It's also good practice to have a mix of global stores and page stores.
subcontracting
in the appletsubcontracting
(subpackage) means that the code of the applet is divided into multiple subpackages, each of which can be independently developed, tested and released, and eventually merged into a complete applet.
Advantages of subcontracting
:
- By loading the applet's resources on-demand, you can reduce the amount of resources on the first load and increase startup speed.
- Multi-team co-development and decoupled collaboration
Type of subcontract
Three types of packages in subcontracts:
- Main Package: the core package of the applet, including the applet's entry files (e.g. , and ) and the resources in the root directory of the applet. The main package is loaded when the app starts.
- Subpackage: packages other than the main package, loaded on demand. Can contain pages, components and other resources.
- Independent sub-package (Independent Subpackage): a special form of sub-package, independent sub-package can be run independently of the main package, for the need to quickly start the small program module.
Subpackage loading rules
After subcontracting, small program project: 1 main package + multiple subcontracts
- Main package: Usually contains only the project start page or tabbar page, and all the public resources needed for the sub-packages.
- Subpackage: contains only pages and private resources (images, js, wxss, wxs...) of the current subpackage
When the applet starts, it will download the main package by default and start the page in the main package, when the user enters a page in the sub-package, the client will download the corresponding sub-package and then display it.
Subcontracting configuration
Suppose we have one main package and two subpackages subpackageA and subpackageB.
The project directory is structured as follows:
├──
├──
├──
├── pages
│ ├── index
│ └── logs
├── subpackageA
│ ├── pages
│ │ ├── pageA1
│ │ │ ├──
│ │ │ ├──
│ │ │ ├──
│ │ │ └──
│ │ ├── pageA2
│ │ ├──
│ │ ├──
│ │ ├──
│ │ └──
├── subpackageB
│ ├── pages
│ │ ├── pageB1
│ │ │ ├──
│ │ │ ├──
│ │ │ ├──
│ │ │ └──
│ │ ├── pageB2
│ │ ├──
│ │ ├──
│ │ ├──
│ │ └──
Configure the subPackages configuration in as follows:
//
{
"pages": [
"pages/index/index",
"pages/logs/logs"
],
"subPackages": [
{
"root": "subpackageA",
"pages": [
"pages/pageA1/pageA1",
"pages/pageA2/pageA2"
]
},
{
"root": "subpackageB",
"pages": [
"pages/pageB1/pageB1",
"pages/pageB2/pageB2"
]
}
]
}
Tip: There is a certain limit to the size of the sub-package, you can check the sub-package size in the "Small Program Developer Tools".
Packing principles
- The applet will install the subpackages configuration for subpackaging, and directories outside of subpackages will be packaged into the main package
- The tabBar page must be in the main package
- Subcontracts cannot be nested directly within each other
Subcontract referencing rules
- Subcontracts can reference public resources within the main package
- Primary packages cannot reference private resources within subpackages.
- Subcontracts cannot reference each other's private resources
independent subcontracting
Independent subcontracting is a special form of subcontracting provided by WeChat applets that allows certain subcontracts to run independently of the main package. This is especially useful for modules that need to start quickly, such as login modules, functionally independent plug-in modules, etc. The use of independent subpackages can significantly improve the startup speed and user experience of small programs.
Characteristics of independent subcontracting:
- Independent operation: independent sub-packages can be started without loading the main package, with independent entry files (e.g. , , , ).
- Fast startup: Since the independent sub-packages do not depend on the main package, the startup speed of these modules can be significantly improved for scenarios that require fast startup.
- Resource isolation: the resources of independent sub-packages are isolated relative to the main package and other sub-packages, which is applicable to modules with more independent functions.
To configure a sub-package as an independent sub-package, only one configuration is needed: independent. see example
//
{
"pages": [
"pages/index/index",
"pages/logs/logs"
],
"subPackages": [
{
"root": "subpackageA",
"pages": [
"pages/pageA1/pageA1",
"pages/pageA2/pageA2"
],
"independent": true
}
]
}
Subcontracting Pre-Download
Sub-package pre-download: it means that the framework automatically downloads the packages that may be needed when you enter a page of the applet.
For example, download packageA when you go to tabBar pageB.
Configured via preloadRule. Like this:
{
"pages": [
"pages/pageA/index",
"pages/pageB/index"
],
"tabBar": {
"list": [
{
"pagePath": "pages/pageB/index",
"text": "PageB"
}
]
},
"subPackages": [
{
"root": "packageA/",
"pages": [
"pageC/index"
]
}
],
"preloadRule": {
"pages/pageB/index": {
// wifi、2g、3g、4g。wifi exclusive of 2g。
"network": "all",
"packages": ["packageA"]
}
}
}