This is the 21st day of my participation in the August More Text Challenge
1. Directory structure
Second, the configuration
A small application will include the two basic configuration files. One is the global configuration file app.json and the page’s own configuration file page.json.
Comments cannot appear in configuration files
2.1 Global Configuration app.json
App. json is the global configuration of the current applet, including all page paths, interface performance, network timeout, bottom TAB, etc.
{ "pages":[ "pages/index2/index2", "pages/index/index", "pages/logs/logs" ], "window":{ "backgroundTextStyle":"dark", "navigationBarBackgroundColor": "#0094ff", "navigationBarTitleText": "WeChat", "navigationBarTextStyle":"black", "enablePullDownRefresh":true }, "tabBar": { "list": [{"pagePath":"pages/index/index", "text":" home ", "iconPath": "ICONS /home.png", "selectedIconPath": "icons/home_active.png" }, { ... } ], "backgroundColor": "#CCC", "color": "#000", "selectedColor": "#0094ff", "borderStyle": "white" } }Copy the code
2.2 Page Configuration Page. json
Page. json indicates the configuration of page.json and applet pages in the page directory.
We can independently define properties for each page, such as the top color, whether to allow a pull-down refresh, etc.
Page. json can only set the contents of some window configuration items in app.json. Page. json overrides the same configuration of window items in app.json.
View layer
WXML (WeiXin Markup Language) is a set of tag Language designed by the framework. Combining with basic components and event system, it can form the structure of the page
3.1 Data Binding
The dynamic data in WXML comes from the data corresponding to the Page.
Simple binding
Data binding uses Mustache syntax to wrap variables around variables that work with:
content
<view> {{ message }} </view> Page({ data: { message: 'Hello MINA! '}})Copy the code
Component properties (need to be in double quotes)
<view id="item-{{id}}"> </view>
Page({
data: {
id: 0
}
})
Copy the code
Control properties (need to be within double quotes)
<view wx:if="{{condition}}"> </view>
Page({
data: {
condition: true
}
})
Copy the code
Keywords (need to be within double quotation marks)
True: Boolean true, representing the true value.
False: Boolean false, indicating false value.
<checkbox checked="{{false}}"> </checkbox>
Copy the code
Special note: Don’t write directlychecked="false"
, evaluates to a string that represents the true value when cast to Boolean.
operation
You can perform simple operations in {{}} in the following ways:
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
The contents of view are 3 + 3 + D.
logic
<view wx:if="{{length > 5}}"> </view>
Copy the code
String operation
<view>{{"hello" + name}}</view>
Page({
data:{
name: 'MINA'
}
})
Copy the code
Data path operation
<view>{{object.key}} {{array[0]}}</view>
Page({
data: {
object: {
key: 'Hello '
},
array: ['MINA']
}
})
Copy the code
combination
You can also compose new objects or arrays directly within Mustache.
An array of
<view wx:for="{{[zero, 1, 2, 3, 4]}}"> {{item}} </view>
Page({
data: {
zero: 0
}
})
Copy the code
The final composition is an array [0, 1, 2, 3, 4].
object
<template is="objectCombine" data="{{for: a, bar: b}}"></template>
Page({
data: {
a: 1,
b: 2
}
})
Copy the code
The resultant object is {for: 1, bar: 2}
You can also use the extension operator… To expand an object
<template is="objectCombine" data="{{... obj1, ... obj2, e: 5}}"></template> Page({ data: { obj1: { a: 1, b: 2 }, obj2: { c: 3, d: 4 } } })Copy the code
The resultant object is {a: 1, b: 2, C: 3, D: 4, e: 5}.
If the key and value of an object are the same, it can also be expressed indirectly.
<template is="objectCombine" data="{{foo, bar}}"></template>
Page({
data: {
foo: 'my-foo',
bar: 'my-bar'
}
})
Copy the code
The resultant object is {foo: ‘my-foo’, bar:’my-bar’}.
Note: The above methods can be combined at will, but if the variable names are the same, the latter will overwrite the former. For example:
<template is="objectCombine" data="{{... obj1, ... obj2, a, c: 6}}"></template> Page({ data: { obj1: { a: 1, b: 2 }, obj2: { b: 3, c: 4 }, a: 5 } })Copy the code
The resultant object is {a: 5, b: 3, c: 6}.
Note: Spaces between curly braces and quotes will eventually be parsed as strings
<view wx:for="{{[1, 3]}} "> {{item}} </view>Copy the code
Is equivalent to
< view wx: for = "{{[1, 2, 3] + '}}" > {{item}} < / view >Copy the code
3.2 List Rendering
wx:for
Bind an array on the component using the WX :for control property to render the component repeatedly using the data from the items in the array.
By default, the subscript variable name of the current item in the default array is index, and the variable name of the current item in the default array is item
Use wx:for-item to specify the variable name of the current element of the array,
We can use wx:for-index to specify the variable name of the array’s current index:
<view wx:for="{{array}}" wx:for-index="i" wx:for-item="value">
{{i}} : {{value}}
</view>>
<view wx:for="{{person}}" wx:for-index="key" wx:for-item="value">
{{key}} : {{value}}
</view>
Copy the code
Page ({/ * * * * / data Page of the initial data: {array: [" name ", "age", "gender"], person: {name: "xiaojian, age: 22, gender:" man "}})Copy the code
Wx :for can also be nested
< view wx: for = "{{,2,3,4,5,6,7,8,9 [1]}}" wx: the for - item = "I" > < view wx: for = "{{,2,3,4,5,6,7,8,9 [1]}}" wx: the for - item = "j" > < the view wx:if="{{j <= i}}"> {{j}} * {{i}} = {{j * i}} </view> </view> </view>Copy the code
Note: When the value of wx:for is not enclosed in two curly braces, it is treated as a string, which is parsed into an array of characters
< view wx: for = "[1, 2, 3, 4, 5]" > {{index}}, {{item}} < / view >Copy the code
Is equivalent to
<view wx:for="{{['[','1','2','3','4','5',']']}}">
{{item}}
</view>
Copy the code
The output
0: [1:1 2:2 3:3 4:4 5:5 6:]Copy the code
Note: Spaces between curly braces and quotes will eventually be parsed as strings
wx:key
If the position of an item in the list changes dynamically or new items are added to the list, and you want the item in the list to maintain its identity and status (such as input input, switch selected status), use wx:key to specify a unique identifier for the item in the list.
The wX :key value is provided in two forms
- String representing a property of the item in the array of the for loop. The value of the property must be a unique string or number in the list and cannot be changed dynamically.
- Reserved keywords
*this
Represents the item itself in the for loop, which requires that the item itself be a unique string or number.
Components with keys are corrected when data changes trigger layer re-rendering, and the framework ensures that they are reordered rather than recreated to ensure that the components remain in their own state and to improve the efficiency of list rendering.
If you don’t providewx:key
, will report onewarning
If you clearly know that the list is static or don’t care about its order, you can ignore it.
3.3 WXSS
WXSS (WeiXin Style Sheets) is a Style language for describing the component styles of WXML.
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.
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 |
Suggestion: Designers can use iPhone6 as the standard for visual draft when developing wechat mini programs.
Note: there will inevitably be some burrs on smaller screens, so try to avoid this when developing.
Style import
Page files in a page folder do not import style files in that folder; all of their files are automatically associated.
To import an external style sheet, you need to import it in the page.wxss file under the page folder:
The @import statement can be used to import an external style sheet, followed by the relative path of the external style sheet to be imported, using; Indicates the end of the statement.
/* page.wxss */
@import "../../styles/commons.wxss";
...
Copy the code
In addition, page.wXSS takes precedence over imported style sheets;
That is, styles written for the same tag in Page.wXSS override styles introduced externally
Note: Comments in WXSS can only be written as /… /
Inline style
Framework components support the use of style and class attributes to control the style of components.
- Style: Static styles are written to class. Styles receive dynamic styles and are parsed at run time. Try to avoid writing static styles into your style to avoid affecting rendering speed.
<view style="color:{{color}};" />
Copy the code
- Class: Used to specify a style rule whose attribute value is a collection of class selector names (style class names) in the style rule. Style class names are not required
.
, style class names are separated by Spaces.
<view class="normal_view" />
Copy the code
Four, components,
1. Basic components
1.1 the view
Equivalent to a DIV in HTML
attribute | type | The default value | mandatory | instructions | Minimum version |
---|---|---|---|---|---|
hover-class | string | none | no | Specifies the style class to press. whenhover-class="none" When, there is no click state effect |
1.0.0 |
hover-stop-propagation | boolean | false | no | Specifies whether to prevent the ancestors of this node from appearing clickable | 1.5.0 |
hover-start-time | number | 50 | no | How long does it take for the click state to appear after holding, in milliseconds | 1.0.0 |
hover-stay-time | number | 400 | no | Click retention time after finger release, in milliseconds | 1.0.0 |
1.2 the text
Text, equivalent to span in HTML
Text can only be nested text
attribute | type | The default value | mandatory | instructions | Minimum version |
---|---|---|---|---|---|
selectable | boolean | false | no | Text optional (deprecated) | 1.1.0 |
user-select | boolean | false | no | Whether text is optional, this property causes the text node to appear inline-block | 2.12.1 |
space | string | no | Display continuous whitespace | 1.4.0 | |
decode | boolean | false | no | Whether the decoding | 1.4.0 |
The legal value of space
value | instructions | Minimum version |
---|---|---|
ensp | Half the size of Chinese characters | |
emsp | Space size of Chinese characters | |
nbsp | The size of the space set according to the font |
1.3 the image
Image label. The default width of the image component is 320px and the default height is 240px
JPG, PNG, SVG, WEBP, GIF and other formats, 2.3.0 support cloud file ID.
Note: this tag is actually a combination of an image from the Web and a background image! And does not support the previous web background image writing method!
attribute | type | The default value | mandatory | instructions |
---|---|---|---|---|
src | string | no | Image resource address | |
mode | string | scaleToFill | no | Picture cropping, zoom mode |
webp | boolean | false | no | WebP format is not parsed by default and only network resources are supported |
lazy-load | boolean | false | no | Images load lazily and load only when they are about to enter a certain range (up and down three screens) |
Valid value of mode
value | instructions |
---|---|
scaleToFill | In zoom mode, the image is scaled without maintaining aspect ratio, so that the width and height of the image are completely stretched to fill the image element |
aspectFit | Zoom mode: Keeps aspect ratio to zoom the image so that the long side of the image is fully displayed. In other words, the image can be displayed completely. |
aspectFill | Zoom mode, keeping aspect ratio zoom image, only the short side of the image can be fully displayed. That is, the image is usually complete only in the horizontal or vertical direction, the other direction will be truncated. |
widthFix | Scale mode, the width is unchanged, the height changes automatically, keep the original image width to height ratio unchanged |
heightFix | Zoom mode, the height is unchanged, the width automatically changes, keep the original image width ratio unchanged |
top | Cropping mode shows only the top area of the image without zooming |
bottom | Cropping mode shows only the bottom area of the image without zooming |
center | Cropping mode, does not zoom the image, only shows the middle area of the image |
left | Cropping mode shows only the left side of the image without zooming |
right | Cropping mode, showing only the right side of the image without zooming |
top left | Cropping mode, does not zoom the image, only shows the upper left side of the image |
top right | Cropping mode, does not zoom the image, only shows the upper right side of the image |
bottom left | Cropping mode, does not zoom the image, only shows the bottom left area of the image |
bottom right | Cropping mode, does not zoom the image, only shows the image of the bottom right area |
1.4 swiper
Wechat has a built-in rote map component. The default width is 100% and the height is 150px.
Slider view container. Only Swiper-Item components can be placed, otherwise undefined behavior will result.
attribute | type | The default value | mandatory | instructions |
---|---|---|---|---|
indicator-dots | boolean | false | no | Whether to display panel indicator points |
indicator-color | color | rgba(0, 0, 0, .3) | no | Indicator color |
indicator-active-color | color | # 000000 | no | The color of the currently selected indicator |
autoplay | boolean | false | no | Whether to switch automatically |
current | number | 0 | no | Index of the current slider |
interval | number | 5000 | no | Auto switch time interval |
duration | number | 500 | no | Slide animation duration |
circular | boolean | false | no | Whether to use cohesive sliding |
vertical | boolean | false | no | Whether the sliding direction is longitudinal |
easing-function | string | “default” | no | Swiper: specifies swiper to switch the slow animation type |
The legal value of easing-function
value | instructions | Minimum version |
---|---|---|
default | Default buffer function | |
linear | Linear animation | |
easeInCubic | Slowly into the animation | |
easeOutCubic | Slow the animation | |
easeInOutCubic | Slow in and slow out animation |
1.5 the navigator
Navigation components, similar to hyperlink tags
attribute | type | The default value | mandatory | instructions | |
---|---|---|---|---|---|
target | string | self | no | On which target the jump occurs, the current applets default | |
url | string | no | Jump links within the current applet | Do not add file name after link. WXML | |
open-type | string | navigate | no | Jump way | |
delta | number | 1 | no | This parameter is valid when open-type is ‘navigateBack’, indicating the number of layers to be rolled back |
The valid value of target
value | instructions |
---|---|
self | Current applets |
miniProgram | Other applets |
Open-type Specifies the valid value
value | instructions |
---|---|
navigate | Keep the current page and go to a page in the application. But you cannot jump to the Tabbar page. |
redirect | Close the current page and switch to a page in the application. However, jumping to the Tabbar page is not allowed |
switchTab | Jump to the tabBar page and close all other non-Tabbar pages |
reLaunch | Close all pages and open to a page within the app |
navigateBack | Close the current page and return to the previous page or multi-level page. throughgetCurrentPagesGet the current page stack and decide how many layers to return to |
exit | Exit the applets,target="miniProgram" Effective when |
1.6 video
Video.
attribute | type | The default value | mandatory | instructions |
---|---|---|---|---|
src | string | is | The address of the resource to play the video, including network path, local temporary path, cloud file ID (2.3.0) | |
duration | number | no | Specify video duration | |
controls | boolean | true | no | Whether to display default play controls (play/pause buttons, play progress, time) |
autoplay | boolean | false | no | Auto play |
loop | boolean | false | no | Whether to loop |
muted | boolean | false | no | Mute Play or Not |
show-mute-btn | boolean | false | no | Whether to display the mute button |
initial-time | number | 0 | no | Specifies the initial playing position of the video |
title | string | no | The title of the video, shown at the top in full screen | |
enable-play-gesture | boolean | false | no | Whether to enable the play gesture, that is, double-click to switch play/pause |
1.7 the button
button
style
attribute | type | The default value | mandatory | instructions |
---|---|---|---|---|
size | string | default | no | Button size |
type | string | default | no | The style type of the button |
plain | boolean | false | no | Whether the button hollow, transparent background color |
disabled | boolean | false | no | Whether to disable |
loading | boolean | false | no | Whether the name is preceded by loading icon |
form-type | string | no | Used forformComponent, click separately to triggerformThe component’s Submit /reset event | |
open-type | string | no | Wechat open ability |
The legal value of size
value | instructions |
---|---|
default | The default size |
mini | Small size |
The valid value of type
value | instructions |
---|---|
primary | green |
default | white |
warn | red |
The valid value of form-type
value | instructions |
---|---|
submit | Submit the form |
reset | Reset the form |
Open-type Specifies the valid value
value | instructions |
---|---|
contact | Open a customer service session. If the user clicks on the message card during the session and returns to the applet, the user can get specific information from the BindContact callback.specify |
share | Trigger user forward, you are advised to read before usingUser guide |
getPhoneNumber | To get the user’s phonenumber, you can get the user’s information from the bindGetPhonenumber callback,specify |
getUserInfo | To getuser information, you can getuser information from the bindGetUserInfo callback |
launchApp | Open APP, you can set the parameters to be transmitted to APP through app-parameter attributespecify |
openSetting | The Authorization Settings page is displayed |
feedback | The Feedback page is displayed, and users can submit and upload the feedbackThe log, developers can log inSmall program management backgroundEnter the page of customer Service Feedback in the left menu to obtain the feedback content |
2. Custom components
Applets allow us to build pages using custom components.
A custom component is like a public page on the Web, and you can extract that public page and use it in other pages and just use a tag.
2.1 Creating a User-defined Component
Similar to a page, a custom component consists of JSON, WXML, WXSS, and JS files
# MyHeader.json
{
"component": true,
"usingComponents": {}
}
Copy the code
# MyHeader.wxml <view class="my_header"> {{initalData}} <view> <! - the label can add custom content - > < slot > < / slot > < / view > < / view >Copy the code
/ / components/MyHeader MyHeader. Js Component ({/ * * * a list of attributes for the Component * initial value, when a page use this Component and declares the initalData this property, The initial value will be replaced * Property name :{* type (type), * value (default) *} */ properties: InitalData :{value:" this is the initial value ", type:String}}, /** * the initial data of the component */ data: {}, /** * the list of components */ methods: {}})Copy the code
.my_header{
color:blue;
background-color: red;
width:200px;
height:200px;
}
Copy the code
2.2 Using Custom Components
# customModule.json { "usingComponents": { "my":".. /.. /components/MyHeader/MyHeader" } }Copy the code
# customModule. WXML <view> <my> Contains data </my> </view>>Copy the code
# customModule. WXML <view initalData=" replace value "> <my> Custom?? </my> </view>>Copy the code
2.3 advanced
Custom component, a navigation bar that adds styles for each click.
# Tabs.json
{
"component": true,
"usingComponents": {}
}
Copy the code
<! -- Tabs.wxml --> <view class="tabs"> <view class="tabs_title"> <view wx:for="{{tabs}}" wx:key="id" class="title_item {{item.isActive? 'active':'none'}}" bindtap="handleItemTap" data-index="{{index}}"> {{item.name}} </view> </view> <view Class ="tab_content"> </view> </view>Copy the code
/* Tabs.wxss */
.tabs{
}
.tabs_title{
display:flex;
padding:10rpx;
}
.title_item{
flex:1;
display:flex;
justify-content: center;
align-items: center;
}
.active{
color:red;
border-top: 5px solid red;
}
Copy the code
// tabs. js Component({/** * Component's property list */ properties: {}, /** * Component's initial data */ data: {tabs:[{id:0, name:" home ", isActive:true}, {id:1, name:" original ", isActive:false}, {id:2, name:" classification ", isActive:false}, {id: 3, name: "about", isActive: false}}, / * * * the method of component list * / the methods: {/ * * * 1. Binding click events requires binding * 2 in methods to get the clicked index * 3. */ handleItemTap(e){console.log(e); */ handleItemTap(e){console.log(e); / / 2. Get clicked the index of the var indexList = e.c. with our fabrication: urrentTarget. Dataset. The index; Var tabs = this.data.tabs; tabs.forEach((v,i)=>i===indexList? v.isActive=true:v.isActive=false); this.setData({ tabs }) } } })Copy the code
use
# customModule.json { "usingComponents": { "Tabs":".. /.. /components/Tabs/Tabs" } }Copy the code
<! -- customModule.wxml --> <Tabs></Tabs>Copy the code
Custom component – Parent passes data to child
Custom components are children, and pages that use custom components are parents
Replace fixed values in custom components with property lists
<! -- customModule.wxml --> <Tabs tabs="{{tabs}}"></Tabs>Copy the code
// customModule.js Page({** ** the initial data of the Page */ data: {tabs:[{id:0, name:" hot ", isActive:true}, {id:1, name:" key ", isActive:false}, {id:2, name:" statement ", isActive:false}, {id:3, name:" feedback ", isActive:false}]}})Copy the code
// Tabs. Js Component({/** * Component's property list */ properties: {Tabs :{type:Array, value:[]}}, /** * Component's initial data */ data: {}, / * * * the method of component list * / the methods: {handleItemTap (e) {... }}})Copy the code
Custom component – Child passes data to parent
According to the above method, the child component uses the parent component’s data, but when the click event is executed, the child component’s data is still modified. So, write to modify the value of the data in the parent component
Solutions:
The child component click event is handed over to the parent component for execution, and the child component is responsible for passing data to the parent
# Tabs.js ... HandleItemTap (e) {/ / 2. Get clicked the index of the var index = e.c. with our fabrication: urrentTarget. Dataset. The index; This. triggerEvent("itemChange",{index}); }...Copy the code
<! -- customModule.wxml --> <! <Tabs Tabs ="{{Tabs}}" binditemChange="handleItemChange"> </Tabs>Copy the code
# customModule.js ... HandleItemChange (e){// console.log(e); Var index = e.daile.index; var index = e.daile.index; Var tabs = this.data.tabs; ForEach ((v, I)=> I ===index? v.isActive=true:v.isActive=false); this.setData({ tabs }) } ...Copy the code
Five, small program life cycle
1. Application life cycle
attribute | type | The default value | mandatory | instructions |
---|---|---|---|---|
onLaunch | function | no | Listen for applet initialization. | |
onShow | function | no | Lifecycle callbacks – Listen for applets to start or cut foreground. | |
onHide | function | no | Life cycle callback – Listen for applets to cut background. | |
onError | function | no | Error listener function. | |
onPageNotFound | function | no | There are no listener functions on the page. | |
onUnhandledRejection | function | no | An unprocessed Promise rejects the event listener function. | |
onThemeChange | function | no | Listen for system topic changes |
2. Page life cycle
attribute | type | The default value | mandatory | 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 | ||
onShareTimeline | function | Users click on the upper right corner to forward to moments | ||
onAddToFavorites | function | Users click on the top right corner to favorites | ||
onPageScroll | function | Handlers for events triggered by page scrolling | ||
onResize | function | Triggered when the page size changes, see detailsResponse to display area changes | ||
onTabItemTap | function | Triggered when you click TAB when the current TAB page is displayed | ||
other | any | Developers can add any function or data toObject Parameter, used in the page functionthis You can visit |