Introduction to the
The running environment of small programs is divided into the rendering layer and the logical layer, in which WXML templates and WXSS styles work in the rendering layer, and JS scripts work in the logical layer. In this way, some front-end frameworks such as jQuery and Zepto can not be used in small programs. Web developers can use the DOM API exposed by various browsers for DOM selection and manipulation.
Global configuration
The app.json file in the root directory of the applets is used for global configuration of wechat applets, determining the path of page files, window performance, setting network timeout, setting multiple tabs, etc.
- Common configuration items
attribute | type | describe |
---|---|---|
pages | string[] | Page path list |
window | Object | Global default window representation |
tabBar | Object | The behavior of the bottom TAB |
networkTimeout | Object | Network timeout |
debug | boolean | Whether to enable the debug mode. By default, the debug mode is disabled |
- Some common configuration options
{
"pages"[// The first item is the default home page"pages/index/index"."pages/logs/index"]."window": {
"navigationBarBackgroundColor": "#ffffff"// Navigation bar background color"navigationBarTextStyle": "black"// Navigation bar title color"navigationBarTitleText": "WeChat"// Navigation bar title text content"backgroundColor": "#eeeeee"// Window background color"backgroundTextStyle": "light"Dark/light},"tabBar": {
"color": "# 666",// Unselected text color"selectedColor": "#ff8928"// The selected text color"list": [{
"pagePath": "pages/index/index"// Page path"text": "Home page"// TAB button text"iconPath": "images/tabBar_img2.png", // Unselected image path"selectedIconPath": "images/tabBar_img1.png"// Select the image path}, {"pagePath": "pages/logs/logs"."text": "Log"}},"networkTimeout": {
"request": 10000, // Wx. request timeout period"downloadFile": 10000 //wx.downloadFile timeout},"debug": true."navigateToMiniProgramAppIdList": [// allows jumping to other applets' appids"wxe5f52902cf4de896"]}Copy the code
Configuration page
Each applet page can also use a.json file of the same name to configure the window representation of the page, and the configuration items in the page will override the same configuration items in the window of app.json.
{
"navigationBarBackgroundColor": "#ffffff"."navigationBarTextStyle": "black"."navigationBarTitleText": "Wechat Interface Function Demonstration"."backgroundColor": "#eeeeee"."backgroundTextStyle": "light"
}
Copy the code
A sitemap configuration
The sitemap.json file in the root directory of the applet is used to configure whether the applet and its pages are allowed to be indexed by wechat.
Register applet
The entire small program only one App instance, is all pages shared. Developers can use the getApp method to get globally unique App samples, get data on the App, or call functions that the developer has registered with the App.
App({onLaunch (options) {// Do something initial when launch.} OnShow (options) {// lifecycle callback -- listen for applets to start or cut foreground // Do something when show.},onHide// Do something when hide.}, onError (MSG) {console.log(MSG)}, OnPageNotFound (res){// Do something when page not found.}, globalData:'I am global data'
})
Copy the code
Const appInstance = getApp() console.log(appinstance.globaldata) // I am global dataCopy the code
Page life cycle
Page({data: {// the initial data of the Page text:"This is page data."
},
onLoad: function// Do some initialize when page load.}, onReady:function// Do something when page ready.}, onShow:function// Do something when page show.}, onHide:function() {// lifecycle callback -- listen on page hide // Do something when page hide.}, onUnload:function// Do something when page close.}, onPullDownRefresh:function() {// Do something when pull down.}, onReachBottom:function() {// Do something when page reach bottom.}, onShareAppMessage:function(res) {// The user clicks in the upper right corner to forwardif (res.from === 'button') {// From the page forward button console.log(res.target)}return {
title: 'Custom Forwarding title',
path: '/page/user? id=123'
}
},
onPageScroll: function() {// Do something when page scroll}, onResize:function() {// when the page size changes, // Do something when page resize}, onTabItemTap(item) {// Console.log (item.index) is triggered when TAB is clicked; Console. log(item.pagepath); // The tabItem page path console.log(item.text); // tabItem button text}})Copy the code
Page routing
The framework maintains all the current pages as a stack
Open a new page
Call THE API wx.navigateTo using the component <navigator URL ="/page/index/index" open-type="navigateTo"/>
Copy the code
Page redirection
Call API wx.redirectTo using the component <navigator URL ="/page/index/index" open-type="redirectTo"/>
Copy the code
The page returns
Call API wx.navigateBack using the component <navigator URL ="/page/index/index" open-type="navigateBack"> The user presses the upper-left return buttonCopy the code
The Tab to switch
Call API wx.switchTab uses the component <navigator open-type="switchTab"/> User toggles TabCopy the code
restart
Call API wx.reLaunch using the component <navigator open-type="reLaunch"/>
Copy the code
modular
Some common code can be separated into a single JS file as a module. Modules can only expose interfaces through module.exports or exports.
// common.js
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name}! SayHello = sayHello exports.sayGoodbye = sayGoodbye var common = require()} module.exports.sayHello = sayHello exports.sayGoodbye = sayGoodbye'common.js')
Page({
helloMINA: function() {
common.sayHello('MINA')
},
goodbyeMINA: function() {
common.sayGoodbye('MINA')}})Copy the code
Commonly used API
The name of the | instructions |
---|---|
wx.showToast | A message dialog box is displayed |
wx.showLoading | The Loading dialog box is displayed |
wx.request | Initiates an HTTPS network request |
wx.uploadFile | Upload local resources to the server |
wx.showShareMenu | Displays a forward button for the current page |
wx.login | Call interface to get login credentials (code) |
wx.checkSession | Check whether the login status has expired |
wx.getAccountInfoSync | Obtain the current account information |
wx.getUserInfo | Obtaining User information |
wx.UserInfo | The user information |
wx.authorize | Initiate authorization requests to users in advance |
wx.setClipboardData | Sets the contents of the system clipboard |
wx.getClipboardData | Gets the contents of the system clipboard |
WXML
WXML (WeiXin Markup Language) is a set of tag Language designed by the framework, which can be combined with the basic components and event system to build the structure of the page.
Data binding
The dynamic data in WXML comes from the data corresponding to the Page, and the variables are wrapped in double braces.
<! --wxml--> <view> {{message}} </view> // page.js Page({ data: { message:'Hello MINA! '}})Copy the code
The list of rendering
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.
<! --wxml--> <view wx:for="{{array}}"> {{item}} </view>
// page.js
Page({
data: {
array: [1, 2, 3, 4, 5]
}
})
Copy the code
Conditions apply colours to a drawing
In the framework, use wx:if=”” to determine if the code block needs to be rendered. 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.
<! --wxml--> <view wx:if="{{view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{{view == 'APP'}}"> APP </view>
<view wx:else="{{view == 'MINA'}}"> MINA </view>
// page.js
Page({
data: {
view: 'MINA'}})Copy the code
Wx: If vs Hidden Because templates in Wx :if may also contain data binding, the framework has a partial rendering process when wx:if’s conditional values are switched, as it ensures that conditional blocks are destroyed or re-rendered when switched. Wx :if is also lazy, so if the initial render condition is false, the framework does nothing and starts partial rendering only when the condition first becomes true. Hidden, by contrast, is much simpler; components are always rendered and simply show and hide. In general, WX :if has a higher switching cost and hidden. There is a higher initial render cost. Therefore, hidden is better if you need to switch frequently, and wx:if is better if conditions are unlikely to change at runtime.
The template
WXML provides templates in which snippets of code can be defined and then invoked in different places.
<! --wxml--> <template name="staffName">
<view>
FirstName: {{firstName}}, LastName: {{lastName}}
</view>
</template>
<template is="staffName" data="{{... staffA}}"></template>
// page.js
Page({
data: {
staffA: {firstName: 'Hulk', lastName: 'Hu'}}})Copy the code
reference
WXML provides two file references: import and include.
- import
Import can use the template defined by the object file in this file
<! -- item.wxml --> <template name="item"> < text > {{text}} < / text > < / template > / < / reference import SRC ="item.wxml"/>
<template is="item" data="{{text: 'forbar'}}"/>
Copy the code
- include
Include can introduce the entire code of the object file except for template, WXS, which is equivalent to copying it to the include location.
<! -- header.wxml --> <view> header </view> <! -- footer.wxml --> <view> footer </view> <! -- index.wxml --> <include src="header.wxml"/>
<view> body </view>
<include src="footer.wxml"/>
Copy the code
WXSS
WXSS (WeiXin Style Sheets) is a Style language for describing the component styles of WXML. Compared to CSS, WXSS extensions have the following features: dimension unit style import
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.
Style import
/** common.wxss **/
.small-p {
padding:5px;
}
/** app.wxss **/
@import "common.wxss";
.middle-p {
padding:15px;
}
Copy the code
Inline style
<view style="color:{{color}};" />
<view class="normal_view" />
Copy the code
The selector
WXS
WXS (WeiXin Script) is a set of scripting language for small programs. Combined with WXML, you can build the structure of a page.
The module
Method 1: WXS labels
<! -- tools.wxs --> var foo ="'hello world' from tools.wxs";
var bar = function (d) {
return d;
}
module.exports = {
FOO: foo,
bar: bar,
};
module.exports.msg = "some msg"; <! -- page/index/index.wxml --> <wxs src=". /.. /tools.wxs" module="tools"/> <view> {{tools.msg}} </view> <view> {{tools.bar(tools.FOO)}} </view> <! --> some MSG'hello world' from tools.wxs
Copy the code
Method 2 :require the function
<! -- tools.wxs --> var foo ="'hello world' from tools.wxs";
var bar = function (d) {
return d;
}
module.exports = {
FOO: foo,
bar: bar,
};
module.exports.msg = "some msg"; <! --logic.wxs--> var tools = require("./tools.wxs");
console.log(tools.FOO);
console.log(tools.bar("logic.wxs")); console.log(tools.msg); <! -- /page/index/index.wxml --> <wxs src=". /.. /logic.wxs" module="logic"/ > <! -- Console output: -->'hello world' from tools.wxs
logic.wxs
some msg
Copy the code
variable
Variables in WXS are all references to values. Undeclared variables that are assigned directly are defined as global variables. If only variables are declared without assigning values, the default value is undefined. Var behaves like javascript, with variable enhancement.
var foo = 1;
var bar = "hello world"; var i; // I === undefined variable names must comply with the following two rules: The first character must be a letter (A-za-z) and the last character must be a letter (A-za-z), the last character must be an underscore (_) and the last character must be a digit (0-9).Copy the code
annotation
<! -- wxml --> <wxs module="sample"< span style = "max-width: 100%; clear: both; min-height: 1em; All WXS code from /* is commented var a = 1; var b = 2; var c ="fake";
</wxs>
Copy the code
The event
Events are the communication mode from the view layer to the logical layer. Events feed user behavior back to the logical layer for processing. Events can be bound to components, and when a triggering event is reached, the corresponding event handler in the logical layer is executed. Event objects can carry additional information such as ID, dataset, and Touches
The event list
type | The trigger condition |
---|---|
touchstart | Finger touch begins |
touchmove | Fingers move after touch |
touchcancel | Finger touch action is interrupted, such as a reminder, popover |
touchend | End of finger touch action |
tap | Touch your finger and leave immediately |
longpress | If the event callback function is specified and the event is triggered, the TAP event will not be triggered |
longtap | After finger touch, leave after more than 350ms (longpress event is recommended instead) |
transitionend | Triggered when WXSS Transition or wx.createAnimation finishes |
animationstart | Emitted when a WXSS animation starts |
animationiteration | Emitted at the end of an iteration of a WXSS animation |
animationend | Emitted when a WXSS animation completes |
touchforcechange | On iPhone devices that support 3D Touch, retiming is triggered |
submit | Submit the form |
scroll | Scroll event |
Event binding is written as a key or value. The key begins with a bind or catch and then follows the event type, such as bindtap or catchtouchstart. The Bind event binding does not prevent bubbling events from bubbling up. The catch event binding prevents bubbling events from bubbling up
component
View the container
The name of the | Functional specifications |
---|---|
movable-view | A removable view container that can be dragged and slid across a page |
cover-image | Image views overlaid on native components |
cover-view | Text views overlaid on top of native components |
movable-area | Movable areas of movable-view |
scroll-view | Scrollable view area |
swiper | Slider view container |
swiper-item | Can only be placed in the swiper component. The width and height are automatically set to 100% |
view | View the container |
Based on the content
The name of the | Functional specifications |
---|---|
icon | icon |
progress | The progress bar |
rich-text | The rich text |
text | The text |
Form components
The name of the | Functional specifications |
---|---|
button | button |
checkbox | Multiple projects |
checkbox-group | Multiple selector, internal by a plurality of checkbox composition |
editor | Rich text editor, you can edit pictures, text |
form | The form |
input | Input box |
label | Used to improve the usability of form components |
picker | Scroll selector that pops up from the bottom |
picker-view | Embed a scroll selector for the page |
picker-view-column | Scroll the selector child |
radio | The radio program |
radio-group | Single selector, composed of multiple radio inside |
slider | Slide selector |
switch | Switch selector |
textarea | Multi-line input box |
navigation
The name of the | Functional specifications |
---|---|
functional-page-navigator | Valid only in plug-ins and used to jump to the plug-in feature page |
navigator | The page link |
Media components
The name of the | Functional specifications |
---|---|
audio | audio |
camera | Camera system |
image | The picture |
live-player | Real-time audio and video playback |
live-pusher | Real-time audio and video recording |
video | video |
The map
The name of the | Functional specifications |
---|---|
map | The map |
The canvas
The name of the | Functional specifications |
---|---|
canvas | The canvas |
Ability to open
The name of the | Functional specifications |
---|---|
web-view | The container that hosts the web page |
ad | Banner ads |
official-account | The public account focuses on components |
open-data | Used to display wechat open data |
Personal summary
- Import modules – sample code
// common.js
function sayHello(name) {
console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
console.log(`Goodbye ${name}! `) } module.exports.sayHello = sayHello; Exports. sayGoodbye = sayGoodbye var common = require(exports.sayGoodbye = sayGoodbye var common = require('common.js')
Page({
helloMINA: function() {
common.sayHello('MINA')
},
goodbyeMINA: function() {
common.sayGoodbye('MINA')}})Copy the code
- jump
Wx. navigateTo({// jump - leave the current page, jump to a page url within the app:'test? id=1'}) wx.redirectto ({// jump - close the current page URL:'test? id=1'
})
Copy the code
- Get global data
var app=getApp()
Copy the code
- Style judgment
<view class="d-row1-cire {{stpe>=2? 'on-2':''}}"></view>
Copy the code
conclusion
If there is something wrong in the article, please leave a comment. Hope this article was helpful to you! Grow together! Progress together! This article is only a personal summary of wechat applets. If you want to view more details, you can go to the official website of wechat applets