This article is my study small program notes.
basis
Applets and ordinary web development differences
- Web pages run in the browser environment and small programs run in the wechat environment
- Applets cannot call DOM and BOM apis. However, small programs can call various apis of wechat environment, such as geolocation, scanning and payment.
- Different development modes
- Apply for an applets development account
- Install applets developer tools
- Create and configure the applets project
Applets project structure
- Pages stores all the pages of the applet
- Utils holds the tool module
- App.js is the entry file for applets
- App. json is the global configuration file for the applet
- App.wxss is a global style file for applets
- Json configuration file for the project
- Sitemap. json configures whether the applets and their pages are allowed to be indexed by wechat
Each page consists of four basic files. Json is the configuration file; .wxml is a template structure file for the page (similar to HTML); .wxss is a style file (similar to CSS) for the current page.
App. Json file
Global configuration file for applets. Pages is used to record the path of the current page, Window global defines all page colors, text colors, etc., style global defines the style version used by the applets component, sitemapLocation is used to specify the location of sitemap.json.
Project. The config. The json file
Project configuration file, setting, projectName, appID, applets account ID.
WXML
Similar to HTML.
- Different label names
- HTML(div,span,img,a)
- WXML(view,text,image,navigator)
- Different attribute nodes
<a href="#">
<navigator url="/pages/home/home"></navigator>
- Comes with vUe-like template syntax
- Data binding.
- List rendering.
- Conditional rendering.
WXSS
Similar to CSS.
-
Added RPX dimension unit
- Rem in CSS requires manual pixel unit conversion.
- The RPX of WXSS is automatically converted to different screen sizes.
-
Global and local styles are provided
- App.wxss is a global style.
- The corresponding.wXSS file in the page is a local style.
-
WXSS supports only some CSS selectors
- Class selector, ID selector, element selector, union selector, descendant selector, pseudo-element selector.
JS in a small program
- app.js
- The entry file for the entire applet, which calls the App() function to launch the entire applet.
- The page.js file
- The Page() function is called to create and run the Page.
- Ordinary.js files
- A plain module file that encapsulates public functions or properties for use by a page.
The host environment
Host environment. The environment on which the program must operate. Mobile wechat is the host environment for small programs,
Communication model
Communication body (render layer and template layer)
- WXML templates and WXSS styles work at the render layer.
- JS scripts work at the logical layer.
Communication model
- Communication between the rendering layer and the logic layer.
- It is forwarded by the wechat client.
- Communication between the logical layer and a third party server.
- It is forwarded by the wechat client.
Operation mechanism
The process of starting a small program
Download applets to local -> parse app.json global configuration file -> execute app.js applets entry file, call APP () to create applets instance -> Render applets home page -> Start complete
Page rendering process
Load the.json configuration file of the parsed Page –> load the.wxml template of the Page and the.wxSS style –> execute the.js file of the Page, call Page() to create the Page instance –> render the Page
component
Wechat applet provides many UI components, such as (not all below) :
- View the container
- View (like div)
- Scrollable view
- Swiper, swiper-item (Carousel container component and carousel item component)
- Based on the content
- Text: Similar to a span in which text is put and worn
selectable
Can only be selected, not in other tags) - Rich-text (rich text component,
nodes
The HTML string in the property can be rendered as a WXML structure.
- Text: Similar to a span in which text is put and worn
- Form components
- Button (button component, through
open-type
Various functions provided by wechat can be called, such as customer service, forwarding, obtaining user authorization, obtaining user information, etc.)
- Button (button component, through
- Media components
- Image (Image component, component default width about 300px, height about 240px)
API
Applets are officially divided into three major classes: event listening API, synchronous API, asynchronous API. The global object in the applet is WX, similar to the window in the browser.
Template syntax
Data binding
Much like Vue, there are two steps:
- Declare it in a data object in the.js file corresponding to the page.
- {{var}}, called Mustache syntax in the little program, is similar to interpolation in Vue.
Unlike Vue, it can be used directly in tag attributes, such as .
event
Common events of applets
- Tap, similar to the click event
- Input, triggered when something is entered in the input box
- Change, triggered when the status changes
Event callback function
The event object
When the event callback is triggered, an event object is received, which has the following properties:
attribute | type | instructions |
---|---|---|
type | String | The event type |
timeStamp | Integer | The number of milliseconds that elapsed between the page opening and the triggering event |
target | Object | The component that triggers the event |
currentTarget | Object | The current component |
detail | Object | Additional information |
touches | Array | Touch events, an array of touch point information that currently stays on the screen |
changedTouches | Array | Touch events, an array of currently changing touch point information |
Assign values to data in data in the event callback
Use the setData function similar to setState in React.
Event pass arguments
Applets cannot pass parameters as Vue does with function names followed by parentheses, because the string in quotes is assumed to be the corresponding function name anyway. Use data-*, as in data-id=”{{2}}” (passing is a string if you don’t use Mustache syntax).
Conditions apply colours to a drawing
wx:if
The if… elif… Else code is as follows:
<view wx:if="{{ type === 1 }}"> 男 </view>
<view wx:elif="{{ type === 2 }}"> 女 </view>
<view wx:else>A secret</view>
Copy the code
Simultaneous control of multiple display hide:
<! -- With blocks, blocks are not rendered into any components -->
<block wx:if="{{ true }}">
<view> view1 </view>
<view> view2 </view>
</block>
Copy the code
Hidden, which controls the display and hiding of elements, as follows:
<view hidden="{{ true }}"> view2 </view>
Copy the code
Wx :if is to dynamically create or remove elements, hidden is control style (display:none/block;) . Use hidden when switching frequently and wx.if when you need to control many elements.
The list of rendering
wx:for
The wX :for code looks like this:
<view wx:for="{{ arr }}">Index of current loop item {{index}} Contents of current loop item {{item}}</view>
Copy the code
Manually specify the index and variable name of the current item:
<view wx:for="{{ arr }}" wx:for-index="idx" wx:for-item="curr">Index of current loop item {{idx}} Contents of current loop item {{curr}}</view>
Copy the code
Similar to the list rendering of :key in Vue, the applet also recommends using a unique value for the key.
<view wx:for="{{ arr }}" wx:key="id">Index of current loop item {{idx}} Contents of current loop item {{curr}}</view>
Copy the code
WXSS
WXSS has most CSS features and also extends RPX and @import.
The RPX unit
Applets unique to solve screen fit size units. Divide the screens of all devices into 750 widths (750rpx). When running on different devices, the applet will automatically convert the RPX style units to the corresponding pixel units for rendering, thus achieving screen adaptation.
Style import
@import "/common/common.wxss";
Copy the code
Covers the rules
App.wxss in the root directory is the global style, and *. WXSS in the page is the local CSS. When the two conflict:
- As a rule of proximity, local styles override global styles.
- The global style is overwritten only when the local style weight is greater than or equal to the global style weight.
Applets global configuration
The app.json file in the root directory is the global configuration file. Common examples are Pages (where the widget page is stored), Window (set the appearance of the widget window globally), tabBar (set the tabBar effect at the bottom of the widget globally), and Style (enable or disable a new version of the component style).
The pull to refresh
<! -- Window configuration -->"EnablePullDownRefresh ": true Enables the drop-down refreshCopy the code
The drop-down bottomed out
<! -- Window configuration -->"OnReachBottomDistance ": 50 The default is 50Copy the code
tabBar
The tabBar is the navigation bar at the top and bottom for switching between pages. A minimum of two and a maximum of five configurations can be configured. The tabBar at the top does not display ICONS but only text. It consists of the following six parts:
- BackgroundColor, the backgroundColor of tabBar.
- SelectedconPath, the image path to display when selected.
- IconPath, the image path if not selected.
- BorderStyle, color of the border on the tabBar.
- SelectedColor, the color of the TAB text when selected.
- Color, the default (unchecked) color of text on TAB.
<! -- same as window -->"tabBar": {
"list": [{"pagePath":"pages/test/test".// tabBar pages must be placed first in the Pages array
"text": "test"
},
{
"pagePath":"pages/index/index"."text": "index"}},Copy the code
Initiate a network request in a small program
For security purposes, applets officially place two restrictions on network requests:
- Only HTTPS interfaces can be requested.
- The domain name of the interface must be added to the trust list.
Applets are not browser environments, so there are no cross-domain issues, and therefore should not be called AJAX requests. Much like many HTTP libraries, the code is as follows:
wx.request({
url: 'https://www.huibox.xyz/api/get'.method: 'GET'.data: {
name: 'jerry'.age: 21
},
success: (res) = >{
console.log(res.data)
}
})
Copy the code
The page navigation
- declarative
<! If you want to jump to tabBar, openTab must be specified as switchTab -->
<navigator url="/pages/home/home" open-type="switchTab">Navigate to the home page</navigator>
<! When jumping to a non-tabbar, the default open-type is avigator, which is the same as normal A links.
<navigator url="/pages/info/info" open-type="navigator">Navigate to the INFO page</navigator>
<! NavigateBack (open type = navigateBack) -->
<navigator open-type="navigator" delta="1">Return to the previous level</navigator>
<! -- Jump with parameters, the same as the browser URL parameter. The parameters passed are available as the first parameter (object) in the lifecycle onLoad function. -->
<navigator url="/pages/info/info? name=bob&age=21">Navigate to the INFO page</navigator>
Copy the code
- programmatic
gotoInfo(){
wx.switchTab({ // To jump to a non-tabbar page, use the wx.navigateTo method
url: '/pages/info/info'.// If you want to pass a parameter, write it the same way as the browser URL
success: function(){
// Execute the code after success
},
fail: function(){
// Code executed after failure
},
complete: function(){
// Code that executes on success or failure}})}gotoBack(){
wx.navigateBack({
delta: 2 // Back up two levels to call the method without passing an argument})}Copy the code
The life cycle of a small program
Classification of life cycles
- Application life cycle (the process of starting the applet -> running it -> destroying it).
onLaunch: function(){}
Is triggered when the initialization of the applet is completeonShow: function(option){}
Triggered when the small program starts or enters the foreground display from the backgroundonHide: function(){}
Triggered when a small program enters the background from the foreground
- Page life cycle (loading > rendering > destruction of the page).
onLoad: function(options){}
// Listen to the page load, a page is called only onceonShow: function(){}
// Listen to the page displayonReady: function(){}
// a page is called only once after the first rendering is completeonHide: function(){}
// The listener page is hiddenonUnload: function(){}
// Listen to the page uninstall
WXS
WXS (WeiXin Script) is a scripting language unique to small programs. Functions defined in page.js cannot be called in WXML, but functions defined in WXS can be called. WXS does not support ES6 or higher syntax. WXS follows the commonJS specification. Because of its limitations, it is often used to write filters to handle strings (instead of filters in Vue). WXS will perform many times better on IOS than JS.