Wechat small program notes
Introduction to the
Why wechat small program?
1. Wechat has a large number of users with high stickiness, so it is easier to develop products in wechat to reach users; 2. The cost of promoting APP or public account is too high. 3. Low cost of development adaptation. 4. It's easy to make small trials and errors and then iterate quickly. 5. Cross-platform.Copy the code
Prepare the environment
Registered account
Suggest the use of a new mailbox, not registered other small procedures or public number. Visit the registration page and complete the registration patiently.Copy the code
Get APPID
Due to the later call wechat applet interface and other functions, it is necessary to obtain the APPID in the developer's applet, so after successful registration, you can log in and then obtain the APPID.Copy the code
The development tools
Wechat applets with developer tools, integrated development preview debugging released in a complete environment. However, since the coding experience is not good, it is suggested to use VS Code + wechat small program editing tool to realize the coding. Vs Code is responsible for coding, while wechat editing tool is responsible for previewCopy the code
Applets structure directory
The goal of the applets framework is to enable developers to develop services with native APP experience in wechat in as simple and efficient a way as possible. The applets framework provides its own view-level description languages WXML and WXSS, as well as JavaScript, and provides a data transfer and event system between the view layer and the logic layer, allowing developers to focus on data and logic.Copy the code
Applets file structure compared to the traditional Web
structure | Traditional web | Wechat applets |
---|---|---|
structure | HTML | WXML |
style | CSS | WXSS |
logic | Javascript | Javascript |
configuration | There is no | JSON |
The above comparison shows that the traditional Web is a three-tier structure. And wechat small program is a four-layer structure, more than a layer of configuration. JsonCopy the code
Basic project directory
Pages -- Page folder index -- home index.js -- home logical file index.json -- Home configuration file index.wxml -- Home HTML file index.wxss -- Home style file Logs - log page... Utils -- third party tools js styles -- public style files components -- lib -- third party library request -- own interface help library app.js -- global entry file for project Json -- Global configuration file app.wxss -- global style file project.config.json -- Project configuration file into appID sitemap.json -- wechat index configuration fileCopy the code
The basic grammar
Data binding
longhand
<view>{{ message }}</view>
Page({
data: {
message: 'Hello World'}})Copy the code
Component attributes
<view id="{{id}}"></view>
Page({
data: {
id: 1,}})Copy the code
The bool type
Don't just say checked=false; it evaluates to a string<checkbox checked="{{false}}"> </checkbox>
Copy the code
operation
The ternary operation
<view hidden="{{flag ? true : false}}"> Hidden </view>
Copy the code
Arithmetic operation
<view> {{a + b}} + {{c}} + d </view>
Page({
data: {
a: 1.b: 2.c: 3}})Copy the code
logic
<view wx:if="{{length > 5}}"> </view>
Copy the code
String operation
<view>{{"hello" + name}}</view>
Page({
data: {name: 'MINA'
}
Copy the code
Pay attention to
Spaces between curly braces and quotes will eventually be parsed as stringsCopy the code
The list of rendering
wx:for
The variable name of the item defaults to item wx:for-item specifies the variable name of the current element of the array. The default variable name is index wx:for-index Specifies the variable name of the current index of the arraywx:key is used to improve array rendering performancewx: The value of the key binding can be selected as follows1.A string that represents a unique attribute in a loop item such aslist: [{id:0.name:"Fried rice"}, {id:1.name:"Fried noodles"}]
wx:key="id"
2.The reserved word *this, which means item itself, *thisMust represent a unique string and array.list: [1.2.3.4.5]
wx:key="*this"
/ / sample
<view wx:for="{{array}}" wx:key="id">
{{index}}: {{item.message}}
</view>
Page({
data: {
array: [{id:0.message: 'foo'}, {id:1.message: 'bar'}]}})Copy the code
block
Rendering a block containing multiple nodes does not end up as a real DOM element<block wx:for="{{[1, 2, 3]}}" wx:key="*this" >
<view> {{index}}: </view>
<view> {{item}} </view>
</block>
Copy the code
Conditions apply colours to a drawing
wx:if
In the framework, use wx:if="{{condition}}" to determine if the code block needs to be rendered:<view wx:if="{{false}}">1</view>
<view wx:elif="{{true}}">2</view>
<view wx:else>3</view>
Copy the code
hidden
<view hidden="{{condition}}"> True </view> like wx:ifSwitching frequently with Hidden Not often used with WX:if<! -- Notice that hidden has no effect when used with block. For example: --><block hidden="{{true}}">1</block>
<block hidden="{{false}}">2</block>
Copy the code
Binding of applets events
A small program to bind events, through the bind keyword. Different components, such as Bindtap Bindinput bindchange, support different events. For details, see the component description. <! -- wxml --><input bindinput="handleInput" /><! -- page --> Page({// Bind events
handleInput: function(e) {
console.log(e);
console.log("The value has been changed."); })/** pay attention */
1.Bind events without arguments without parentheses < INPUT bindinput="handleInput(100)" />
2.Event values are passed by tag custom attributes and value < INPUT bindinput="handleInput" data-item="100" />
3.Gets data when the event is triggeredhandleInput: function(e) {
// {item:100}
console.log(e.currentTarget.dataset)
// Enter the value of the box
console.log(e.detail.value);
}
Copy the code
Style WXSS
WXSS(WeiXin Style Sheets) is a Style language for describing the component styles of WXML. Compared with CSS, WXSS has the following extended features: 1. Responsive length units 2. Style importCopy the code
Size of the unit
RPX (Responsive Pixel) : ADAPTS to the screen width. Specify a screen width of 750rpx. For example, on iPhone6, the screen width is 375px and there are 750 physical pixels, then 750rpx = 375px = 750 physical pixels and 1rpx = 0.5px = 1 physical pixel. Suggestion: When developing wechat mini program, designers can use iPhone6 as the standard visual draft: 1. 2. Calculate the scale 750rpx = pageWidth px, so 1px=750rpx/pageWidth. 3. In less file, just put px => 750/pageWidth RPX in the design draft.Copy the code
equipment | RPX convert px (screen width /750) | Convert PX to RPX (750/ screen width) |
---|---|---|
iPhone5 | 1 the RPX = 0.42 px | 1 px = 2.34 the RPX |
iPhone6 | 1 the RPX = 0.5 px | 1px = 2rpx |
iPhone6 Plus | 1 the RPX = 0.552 px | 1 px = 1.81 the RPX |
Style import
WXSS supports style import directly. It can also be used with imports in less. use@importStatements can import external stylesheets, and only relative paths are supported. /** common.wxss **/.small-p {padding: 5px;
}
/** app.wxss **/
@import "common.wxss";
.middle-p {
padding:15px;
}
Copy the code
The selector
Note in particular that applets do not support wildcards * so the following code is not valid! * {margin:0;
padding:0;
box-sizing:border-box;
}
Copy the code
Currently supported selectors are:
The selector | The sample | The sample description |
---|---|---|
.class | .intro | Select all components that have class=intro |
#id | #firstname | Select the component that has id= firstName |
element | view | Select all view components |
element, element | view, checkbox | Select view components for all documents and all checkbox components |
nth-child(n) | view:nth-child(n) | Select a label for an index |
::after | view::after | Insert content after the View component |
::before | view::before | Insert content in front of the View component |
Common components
view
Instead of the original div tag<view hover-class="h-class">Let me try it</view>
Copy the code
text
1. Text label 2. Can only nest text 3. Spaces and carriage returns can be encodedCopy the code
The property name | type | The default value | instructions |
---|---|---|---|
selectable | Boolean | false | Whether text is optional |
decode | Boolean | false | Whether the decoding |
<! -- Sample code -->
<text selectable="{{false}}" decode="{{false}}">
普 tong</text>
Copy the code
image
The default width of image component is 320px and the default height is 240px. 2. Lazy loading is supportedCopy the code
The property name | type | The default value | instructions |
---|---|---|---|
src | String | Image resource address | |
mode | String | ‘scaleToFill’ | Picture cropping, zoom mode |
lazy-load | Boolean | false | Lazy loading of images |
Valid values of mode: Mode has 13 modes, 4 of which are scale mode and 9 of which are cropping mode.Copy the code
model | value | instructions |
---|---|---|
The zoom | scaleToFill | Scale the image without maintaining aspect ratio, so that the width and height of the image are completely stretched to fill the image element |
The zoom | aspectFit | Maintain aspect ratio to scale the image so that the long sides of the image are fully displayed. |
The zoom | aspectFill | Keep aspect ratio zooming in and out of the image so that only the short edges of the image are fully visible. |
The zoom | widthFix | The width is unchanged, and the height changes automatically, keeping the width to height ratio unchanged |
tailoring | top | Show only the top area of the image without zooming |
tailoring | bottom | Shows only the bottom area of the image without zooming |
tailoring | center | Shows only the middle area of the image without zooming |
tailoring | left | Shows only the left side of the image without zooming |
tailoring | right | Shows only the right side of the image without zooming |
tailoring | top left | Shows only the upper left side of the image without scaling |
tailoring | top right | Shows only the upper right side of the image without zooming |
tailoring | bottom left | Shows only the lower left area of the image without zooming |
tailoring | bottom right | Shows only the lower right area of the image without zooming |
Custom Components
Custom component applets like vue or React allow you to build pages using custom components.Copy the code
Create custom components
Similar to the page, a custom component consists of JSON WXML WXSS JS 4 files. You can quickly create the file structure of the component in wechat developer tools in the folder Components /myHeader, create the component named myHeaderCopy the code
Announcement component
First you need to customize the component declaration myheader. json {in the component's JSON file."component": true
}
Copy the code
Edit component
At the same time, write the component template in the WXML file of the component and add the component style slot to the WXSS file, similar to slot myHeader.wxml in vUE<! This is the internal WXML structure of the custom component.
<view class="inner">
{{innerText}}
<slot></slot>
</view>Write styles in component WXSS files Note: ID selectors, attribute selectors, and tag name selectors should not be used in component WXSS. Myheader. WXSS /* The style here applies only to this custom component */. Inner {color: red; }Copy the code
Certified components
In the Component's JS file, you need to use Component() to register the Component and provide its property definitions, internal data, and custom methods myheader.js Component({properties: {
// Here we define the innerText property, whose value can be specified when the component uses it
innerText: {
// The desired data type is string
type: String.value: 'default value',}},data: {
// Here is some internal component data
someData: {}},methods: {
// Here is a custom method
customMethod: function(){}}})Copy the code
Declaration introduces custom components
The first step is to declare a reference in the JSON file of the page. Also provide the corresponding component name and component path index.wxml {// Reference declaration
"usingComponents": {
// The name of the component to use // the path to the component
"my-header":"/components/myHeader/myHeader"}}Copy the code
Use custom components in the page
<view>
<! The following is a reference to a custom component -->
<my-header inner-text="Some text">
<view>Used in place of slot</view>
</my-header>
</view>
Copy the code
Component – Custom component parameter transfer
1. The parent component passes parameters to the child component in the form of attributes. 2Copy the code
process
1. The parent component passes data {{tabs}} to the tabItems property of the child component. 2. The child component fires the MyTap event in bindMyTap 1. 4. Parent -> child dynamically pass this. SelectComponent ("#tabs")Copy the code
Parent component code
<tabs tabItems="{{tabs}}" bindmytap="onMyTab"></tabs>
// page.js
data: {
tabs:[
{name:"Experience problems"},
{name:"Complaint of goods and merchants"}},onMyTab(e){
console.log(e.detail); },...Copy the code
Subcomponent code
// com.wxml
<view class="tabs">
<view class="tab_title" >
<block wx:for="{{tabItems}}" wx:key="{{item}}">
<view bindtap="handleItemActive" data-index="{{index}}">{{item.name}}</view>
</block>
</view>
</view>
// com.js
Component({
properties: {
tabItems: {type:Array.value: []}},/** * The initial data of the component */
data: {},/** * list of component methods */
methods: {
handleItemActive(e){
this.triggerEvent('mytap'.'haha'); }}})Copy the code
Applets life cycle
Application life cycle and page life cycleCopy the code
Application life cycle
attribute | type | The default value | mandatory | instructions |
---|---|---|---|---|
onLaunch | function | no | Listen for applet initialization. | |
onShow | function | no | Listen for applets to start or cut foreground. | |
onHide | function | no | Listen to the applet cut background | |
onError | function | no | Error listener function | |
onPageNotFound | function | no | There are no listener functions on the page |
Page life cycle
attribute | type | instructions |
---|---|---|
data | Object | Initial data for the page |
onLoad | function | Lifecycle callbacks – Listen for page loads |
onShow | function | Lifecycle callbacks – Listen for page display |
onReady | function | Lifecycle callback – Listens for the page to finish rendering for the first time |
onHide | function | Lifecycle callbacks – Listen for page hiding |
onUnload | function | Lifecycle callbacks – Listen for page unloads |
onPullDownRefresh | function | Monitor user pull down actions |
onReachBottom | function | A handler for a pull-down event on the page |
onShareAppMessage | function | The user clicks in the upper right corner to forward |
onPageScroll | function | Handlers for events triggered by page scrolling |
onResize | function | Triggered when the page size changes, see response to display area changes |
onTabItemTap | function | Triggered when you click TAB when the current TAB page is displayed |