[Mini Programs] Basic Grammar Explanation of WeChat Mini Programs (1)

I. Overview

WeChat Mini Program is a platform for quickly building applications, and its basic syntax mainly includes the following aspects:

  • WXML: The template language of the WeChat applet, similar to HTML, used to describe the page structure.

  • WXSS: The style language of WeChat applets, similar to CSS, is used to describe page styles.

  • JS: The scripting language of the WeChat applet, used to realize the logic and interaction of the page.

  • JSON: The configuration file of the WeChat Mini Program, which is used to configure the global configuration, page configuration and other information of the Mini Program.

In the WeChat applet, you can set the structure and style of the page by using tags and attributes in WXML; write logic and event processing functions in JS to achieve page interaction and dynamic effects; configure the global information of the applet in JSON And page configuration information, such as page path, title bar color, etc. At the same time, the WeChat applet also provides some built-in components and APIs, which can easily realize various functions and effects, such as audio, video, map, code scanning, etc.

insert image description here

2. Small program code composition

​A small program consists of configuration code JSONfiles, template code WXMLfiles , style code WXSSfiles, and logic code JavaScriptfiles .

The applet code mainly consists of four parts:

  • JSON(JavaScript Object Notation) 配置: JSON is a data format, not a programming language. In applets, JSON plays the role of static configuration.

  • WXML(WeiXin Markup Language)模板: A markup language similar to HTML, used to describe the structure level of applets.

  • WXSS(WeiXin Style Sheets)样式: A style sheet language similar to CSS, used to set the style and layout of applets.

  • JS(JavaScript)逻辑交互: Used to realize the logic and interaction effects of the applet.

The above three parts correspond to the structure layer , style layer and behavior layer of the applet respectively , and together they form the overall code of the applet. In addition, the applet can also use JSON files to configure some global information, such as window title, page path, etc.

1) JSON configuration

JSON (JavaScript Object Notation) is a lightweight data exchange format that is easy to understand, read, write, and parse. It is widely used in web applications, mobile applications, and other fields. In the applet, JSON is used to configure various attributes and information of the applet.

The JSON configuration of the applet includes two parts:

  • app.jsonand page configuration files. Among them, is the global configuration fileapp.json of the applet , which is used to configure the window properties, bottom navigation bar properties, page path and other information of the applet.
  • The configuration file of the page includes .json, .wxml, .wxss, and .jsfour files, which are used to configure the data, structure, style and behavior of the page.

The role of JSON configuration mainly has the following aspects:

  1. Configure the basic information of the applet : the title of the applet, the size of the window, the style of the navigation bar, etc.
  2. Configure page path and navigation bar information : configure the page path of the applet in the app.json file, and you can jump to the page through the navigation bar.
  3. Configure the bottom navigation bar : You can configure the bottom navigation bar of the applet through the tabBar property, so that users can quickly switch pages.
  4. Configure the data and structure of the page : configure the data and structure information of the page in the .json and .wxml files of the page, including the title, background color, layout, etc. of the page.
  5. Configure the style and behavior of the page : configure the style and behavior information of the page in the .wxss and .js files of the page, including the font, color, animation, etc. of the page.

By configuring the JSON file of the applet, developers can control the appearance and behavior of the applet, thereby improving the user experience of the applet.

Let's look at an example JSON configuration for an applet:

{
    
    
  "pages": [
    "pages/index/index",
    "pages/about/about"
  ],
  "window": {
    
    
    "navigationBarTitleText": "小程序示例",
    "navigationBarBackgroundColor": "#ffffff",
    "navigationBarTextStyle": "black"
  },
  "tabBar": {
    
    
    "color": "#999999",
    "selectedColor": "#000000",
    "backgroundColor": "#ffffff",
    "list": [
      {
    
    
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "images/home.png",
        "selectedIconPath": "images/home-active.png"
      },
      {
    
    
        "pagePath": "pages/about/about",
        "text": "关于",
        "iconPath": "images/about.png",
        "selectedIconPath": "images/about-active.png"
      }
    ]
  }
}

In this example, we define configuration information for three parts of the applet:

  • "pages": Defines the page path of the applet, where you can specify each page of the applet.

  • "window": Defines the window properties of the applet, where you can set the title of the applet, the background color of the navigation bar, etc.

  • "tabBar": Defines the properties of the bottom navigation bar of the applet, where you can set the color of the bottom navigation bar, the selected color, etc., as well as the text and icons of each navigation bar.

The configuration information of the above three parts is presented in JSON format, and the applet can determine the structure, style and behavior of the applet by reading these configuration files.

2) WXML template

WXML(WeiXin Markup Language)It is a markup language similar to HTML , which is a part of applet development. It is used to describe the structure and components of applets, and static pages can be written like HTML.

  • The WXML template consists of a series of tags and attributes used to describe the structure and content of the applet page. Similar to HTML, WXML is also a hierarchical structure, and tags can be nested to form a parent-child relationship. In WXML, each tag has a corresponding attribute, which is used to control the display and behavior of the tag.

  • Different from HTML , the label and attribute names of WXML are slightly different from HTML. At the same time, WXML also provides some special components for describing special functions of applets, such as navigation bar, pull-down refresh, etc.

The advantages of WXML templates are:

  • Conciseness : WXML uses a syntax similar to HTML, enabling developers to achieve page effects with less code.

  • Specifically designed for applets : WXML provides many tags and components specially designed for applets, which can easily realize various functions of applets.

  • Convenient interaction with JS : WXML can interact with JS by binding data, events, etc., so that the data and behavior of the page can be easily controlled.

  • Component-based development : WXML supports component-based development, which can split a page into multiple components, reduce code coupling, and improve code reusability.

Through the WXML template, developers can easily create the page structure and layout of the Mini Program, and realize various functions and interactive effects of the Mini Program.

1. Commonly used tags in WXML templates

  • <view>: View container, similar to <div>the tag .

  • <text>: Text container, used to display text content.

  • <image>: Image container, used to display images.

  • <block>: Block-level container, which can be <view>used , but will not generate extra nodes in the page.

  • <swiper>: Slider view container, used to display content such as carousels.

  • <scroll-view>: A scrollable view container, which can be scrolled to display a large amount of data.

  • <icon>: icon container, used to display small icons.

  • <button>: Button container for user interaction.

  • <input>: Input box container, used to receive user input.

  • <checkbox>: Check box container, used to select multiple options.

  • <radio>: Radio box container, used to select an option.

  • <picker>: A selector container, used to select one or more options from the preset options.

  • <form>: Form container, used to collect data entered by the user.

  • <navigator>: Navigation container, used to realize page jump.

The above are commonly used tags in WXML templates, and of course there are other tags and attributes, which can be selected and used according to specific needs.

2. The difference between the view tag and the block tag

In WXML templates, <view>and <block>are container tags used to wrap other components or elements, but they have some differences in rendering and performance:

  • Rendering difference : <view>It will be converted to diva tag , <block>but will not be converted, it is just a pure container tag, and no extra nodes will be generated in the page.

  • Styling differences : The style categories of<view> and are both block-level elements, but their default styles may differ in some cases. <block>For example, <view>there are some margins and padding by default, <block>but not, which may affect the layout effect.

  • Usage scenarios : There are also some differences in<view> usage scenarios, which are more suitable for layout containers, such as the main structure of the page, list items, etc.; and are more suitable for temporarily wrapping some elements, such as in a conditional judgment, wrap some elements Package etc. as a whole.<block><view><block>

To sum up, <view>and <block>are container tags with similar functions, but they may have some differences in rendering, style and usage scenarios, developers can choose and use according to specific needs.

Here is an example of a simple WXML template:

<!-- index.wxml -->
<view class="container">
  <view class="title">Hello World!</view>
  <image src="../../images/avatar.png" class="avatar"></image>
  <view class="description">This is a demo for WXML template.</view>
  <button class="button" bindtap="onTap">Click Me</button>
</view>

In this example, <view>the label represents a view container that can nest other labels. <image>Tag represents an image tag for displaying images. <button>The label represents a button and is used to trigger events.

  • WXMLIn , each label can have some attributes, which are used to control the display and behavior of the label. For example, classthe attribute is used to specify the style class of the label, srcthe attribute is used to specify the picture URL, and bindtapthe attribute is used to specify the click event of the button.

  • In this example onTapis a function defined in a JavaScript file that handles button click events. By binding events in WXML, developers can easily realize the interactive effects of applets.

  • The syntax of WXML is similar to HTML, but there are some differences. In WXML, you cannot use HTML tags and attributes, but use the tags and attributes provided by the applet. At the same time, WXML also supports some special syntax, such as { { }}double curly braces for data binding, wx:ifconditional rendering, wx:forlist rendering, etc., which can easily achieve complex page effects.

3. Condition control

1. wx:if conditional control

In the WXML template, you can use wx:ifconditional rendering tags to achieve the effect of displaying different content according to conditions. Here is an example of a WXML template condition:

<!-- index.wxml -->
<view class="container">
  <view wx:if="{
     
     {isShow}}" class="title">Hello World!</view>
  <view wx:if="{
     
     {!isShow}}" class="title">Goodbye World!</view>
  <button class="button" bindtap="onToggle">Toggle</button>
</view>

In this example, we define a isShowdata item to control the display of different titles. In WXML, we use the wx:ifconditional rendering tag isShowto determine which title to display based on the value of .

In the JavaScript file, we define a onTogglefunction to toggle isShowthe value of . When the user clicks the button, isShowthe value of will change, thereby realizing the switching effect of the title.

// index.js
Page({
    
    
  data: {
    
    
    isShow: true
  },
  onToggle: function() {
    
    
    this.setData({
    
    
      isShow: !this.data.isShow
    })
  }
})

In the JavaScript file, we use setDatathe function to update the value of isShow, which triggers a re-render of the template.

By using wx:ifconditional rendering tags, we can easily realize the effect of displaying different content according to conditions, thereby enhancing the interactivity and usability of the applet.

2. wx:if/else conditional control

In the WXML template, in addition to using the wx:ifconditional rendering tag, you can also use wx:elsethe tag to implement elsethe branch . Here is if/elsean example of :

<!-- index.wxml -->
<view class="container">
  <view class="title">Welcome to My Page!</view>
  <view wx:if="{
     
     {isVIP}}" class="subtitle">VIP User</view>
  <view wx:else class="subtitle">Normal User</view>
</view>

<!--elif-->
<view wx:if="{
     
     {view == 'WEBVIEW'}}"> WEBVIEW </view>
<view wx:elif="{
     
     {view == 'APP'}}"> APP </view>
<view wx:else="{
     
     {view == 'MINA'}}"> MINA </view>

In this example, we define a isVIPdata item to control the display of different user types. In WXML, we use wx:ifand wx:elsetags to judge and display different user types according to the value of isVIP.

In the JavaScript file, we define a onLoadfunction to initialize the isVIP data item.

// index.js
Page({
    
    
  data: {
    
    
    isVIP: true
  },
  onLoad: function () {
    
    
  }
})

In JavaScript files, we can initialize data items in various ways, such as fetching data from the server, fetching data from local cache, fetching data from user input, and so on.

By using wx:ifand wx:elsetags, we can conveniently realize elsethe branch , thereby enhancing the usability and interactivity of the applet.

3. wx:for loop

In the WXML template, you can use wx:forthe list rendering tag to realize the effect of rendering the list according to the data cycle. Here is an example of a WXML template loop:

<!-- index.wxml -->
<view class="container">
  <view class="title">List:</view>
  <view wx:for="{
     
     {list}}" wx:key="id" class="item">{
   
   {item.name}}</view>
</view>

In this example, we define a listdata item, which is an array containing some objects. In WXML, we use wx:forthe list- rendering tag, iterate over listeach object in the array, and render the list items based on the object's properties.

In the JavaScript file, we define a onLoadfunction that initializes listthe data item.

// index.js
Page({
    
    
  data: {
    
    
    list: [
      {
    
     id: 1, name: 'Item 1' },
      {
    
     id: 2, name: 'Item 2' },
      {
    
     id: 3, name: 'Item 3' }
    ]
  },
  onLoad: function () {
    
    
  }
})

In JavaScript files, we can initialize data items in various ways, such as fetching data from the server, fetching data from local cache, fetching data from user input, and so on.

By using wx:forthe list rendering tag, we can easily achieve the effect of rendering the list according to the data cycle, thereby enhancing the usability and interactivity of the applet.

3) WXSS style

WXSS (WeiXin Style Sheets) is a style language for applets, used to control the appearance and layout of the applet interface. It is a CSS extension language with a CSS-like syntax but with some peculiarities and limitations of its own.

WXSS supports most CSS syntax and features, such as selectors, box model, floats, positioning, fonts, backgrounds, colors, animations, and more. Currently supported selectors are:

Selector sample Sample description
.class .intro Select all components with class="intro"
#id #firstname Select the component with id="firstname"
element view Select all view components
element, element view, checkbox Selects all document view components and all checkbox components
::after view::after Insert content behind the view component
::before view::before Insert content before the view component

Global styles and local styles :

global styleIf you want to use the same style in multiple pages or components, you can use the global style ( ) or public style ( common style) function provided by the applet . Specifically, you can define global styles app.wxssin or define common styles in a separate wxss file , and then reference them in the style tags of the page or component.

The way to define global styles is to define style classes app.wxssin , which can be used in the whole applet. For example:

/* app.wxss */
.global-text {
    
    
  font-size: 16px;
  color: #333;
}

You can then use this style class in any page or component:

/* 页面或组件的样式标签 */
<view class="global-text">这是全局样式中定义的文本样式</view>

The way to define common styles is to define style classes in a separate wxss file, and then reference them in the style tag of the page or component. For example:

/* common.wxss */
.common-button {
    
    
  background-color: #00c2ff;
  color: #fff;
  padding: 10px 20px;
}

/* 页面或组件的样式标签 */
<view class="common-button">这是公共样式中定义的按钮样式</view>

Please note that if you use public styles , you need to include this file in your page or component. For example, setting usingComponentsthe field :

/* 页面的js文件 */
Page({
    
    
  config: {
    
    
    usingComponents: {
    
    
      'common-style': '/path/to/common.wxss'
    }
  }
})

Then use @importthe statement to import the file:

/* 页面或组件的样式标签 */
@import 'common-style';

<view class="common-button">这是公共样式中定义的按钮样式</view>

In addition to supporting CSS syntax and features, WXSS also has some of its own features and extensions, such as:

  • Supports size units rpxand can be automatically scaled according to the screen width;
  • Support importing external style files, you can use @importkeywords ;
  • Support style inheritance, you can use inheritand initialvalue;
  • Support global style override, you can use !importantthe keyword .

By using WXSS, we can easily control the appearance and layout of the applet interface, so as to achieve various visual effects and interactive effects.

Here is an example of basic WXSS styling:

/* 定义样式 */
.page {
    
    
  background-color: #fff;
  color: #333;
  font-size: 14px;
  padding: 10px;
}

.title {
    
    
  font-weight: bold;
  font-size: 18px;
  margin-bottom: 10px;
}

.subtitle {
    
    
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 8px;
}

.text {
    
    
  line-height: 1.5;
  margin-bottom: 10px;
}

.link {
    
    
  color: #00c2ff;
  text-decoration: none;
}

.link:hover {
    
    
  text-decoration: underline;
}

/* 使用样式 */
<view class="page">
  <view class="title">这是标题</view>
  <view class="subtitle">这是副标题</view>
  <view class="text">这是文本内容</view>
  <a class="link" href="https://www.example.com">这是链接</a>
</view>

In this example, some basic styles are defined, such as background color, font size, margin and color, etc., and different style classes are applied to different elements. When using a style, you only need to add the corresponding class name to the corresponding element.

4) JS (JavaScript) logic interaction

The JS in the WeChat applet is mainly used to realize functions such as logical interaction and data processing of the page. Here are some common ways to interact with JS:

  • Data binding and event binding : In WXML, { {}}data binding is performed through syntax, in WXSS, { {}}syntax binding style is used, and page data can also be updated using setDatathe method . For event binding, you can use bindand catchprefixes to bind event handlers.

  • API calls : WeChat applets provide a wealth of API interfaces, which can be called through JS codes to implement various functions, such as obtaining user information, calling payment interfaces, and sending requests.

  • Lifecycle functions : WeChat applets provide multiple lifecycle functions, which can perform corresponding operations in different stages, such as onLoad, onShow, onReady, onHide, onUnloadand so on.

  • Custom components: Custom components can encapsulate a set of WXML, WXSS and JS into an independent component, which can be reused in different pages. Attributes and events can be used in custom components to achieve data transfer and interaction.

In short, the JS in the WeChat applet is mainly used to realize the logical interaction and data processing of the page, and different functions can be realized through data binding, event binding, API call, life cycle function, and custom components. It should be noted that in order to improve the performance and experience of the applet, unnecessary operations and network requests should be minimized, and frequent page data updates should be avoided.

The following is an example of a simple WeChat applet JS logic interaction:

1. WXML file

<view>{
   
   {message}}</view>
<button bindtap="changeMessage">点击我修改消息</button>

2. JS file

Page({
    
    
  data: {
    
    
    message: 'Hello World'
  },
  changeMessage: function () {
    
    
    this.setData({
    
    
      message: '你好,世界!'
    })
  }
})

In this example, we define a viewelement button. viewElements are used to display a message and buttonelements are used to trigger an event. In the JS file, we define an event handler changeMessagecalled , which will be triggered when the user clicks the button. changeMessageThe function uses setDatathe method to update messagethe data, changing it to "Hello, world!". Since messagethe data has been bound to the view element, when the data is updated, the message on the page will be updated accordingly.

In this example, we demonstrate the basic usage of data binding, event binding and API calls. Among them, setDatathe method is used to update the page data, and the data update can be implemented in the changeMessage event processing function; it bindtapis used to bind the click event, and this attribute can be used on the button element to bind the event processing function.

1. Life cycle function

The execution order of the lifecycle functions of WeChat applets is as follows:

  • onLaunch: When the initialization of the applet is completed, the onLaunch function will be triggered. This is the first function in the entire life cycle of the applet and is executed only once. Generally used to do some initialization operations.

  • onShow: When the applet starts or enters the foreground from the background, the onShow function will be triggered. In the applet life cycle, the onShow function may be executed multiple times. It is generally used to obtain status information of applets.

  • onPageLoadAnd onReady: When the Mini Program page is loaded, the onLoad and onReady functions will be triggered in sequence. onLoadFunctions fire when the page loads, and onReadyfunctions fire when the page's initial render completes. onPageLoadGenerally used to initialize page data. onReadyGenerally used for page layout operations.

  • onTabItemTap: When the user taps the tab bar, the onTabItemTap function will be triggered.

  • onPullDownRefresh: When the user pulls down to refresh the page, the onPullDownRefresh function will be triggered.

  • onReachBottom: When the page scrolls to the bottom, the onReachBottom function is triggered.

  • onHide: When the applet enters the background from the foreground, the onHide function will be triggered.

  • onUnload: When the applet exits, the onUnload function will be triggered.

Taking the page as an example, you can define the corresponding life cycle function in the .js file:

Page({
    
    
  // 页面的初始数据
  data: {
    
    
    message: 'Hello World!'
  },
  // 生命周期函数--监听页面加载
  onLoad: function (options) {
    
    
    console.log('页面加载完成')
  },
  // 生命周期函数--监听页面初次渲染完成
  onReady: function () {
    
    
    console.log('页面初次渲染完成')
  },
  // 生命周期函数--监听页面显示
  onShow: function () {
    
    
    console.log('页面显示')
  },
  // 生命周期函数--监听页面隐藏
  onHide: function () {
    
    
    console.log('页面隐藏')
  },
  // 生命周期函数--监听页面卸载
  onUnload: function () {
    
    
    console.log('页面卸载')
  },
  // 页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh: function () {
    
    
    console.log('用户下拉刷新')
  },
  // 页面上拉触底事件的处理函数
  onReachBottom: function () {
    
    
    console.log('页面上拉触底')
  },
  // 用户点击右上角分享
  onShareAppMessage: function () {
    
    
    console.log('用户点击分享')
    return {
    
    
      title: '小程序分享',
      path: '/pages/index/index'
    }
  }
})

Components can also be configured using the corresponding lifecycle functions. It should be noted that in the applet, the life cycle function of the component will be affected by the parent component, and the specific execution sequence will be affected by the nesting relationship of the components.

2. Event function

In WeChat applets, event functions refer to functions that are executed when an event occurs in the applet, such as the user clicking a button, swiping a page, inputting content, and so on. The event function can be bound and triggered through the bind or catch attribute in the wxss style sheet and the event object in the wxml template.

Common event functions in WeChat applets are:

  • bindtap/catchtap: Click event function, triggered when the user clicks on an element.

bindtapand catchtapare both properties used to bind the click event, the difference between them is that the event bubbling is handled differently.

Specifically:

- bindtap是捕获型事件,触发事件后先执行当前元素的事件函数,再向上冒泡执行父元素的事件函数。如果父元素也绑定了bindtap事件,那么该事件也会被触发执行。

- catchtap是冒泡型事件,触发事件后先执行父元素的事件函数,再向下捕获执行当前元素的事件函数。如果当前元素绑定了catchtap事件,那么该事件会阻止冒泡,不会继续向上执行父元素的事件函数。
  • bindinput/catchinput: Input event function, triggered when the user enters content in the input box. The difference between the two is the same as above.

  • bindscroll/catchscroll: Scroll event function, triggered when the user slides on the page. The difference between the two is the same as above.

  • bindlongpress/catchlongpress: Long press event function, triggered when the user presses an element for a long time. The difference between the two is the same as above.

  • bindsubmit/catchsubmit: form submit event function, triggered when the user submits the form. The difference between the two is the same as above.

  • bindcancel/catchcancel: form cancel event function, triggered when the user cancels the form. The difference between the two is the same as above.

In addition to the above common event functions, the WeChat Mini Program also provides many other event functions, for details, please refer to the WeChat Mini Program Development Document.

When writing event functions, you need to pay attention to the following points:

  • The name of the event function should be consistent with the property name of the bound event so that the event can be triggered correctly.

  • In the event function, the event object can be used to obtain the relevant information of the event, such as event type, trigger element, trigger position, etc.

  • The this keyword can be used in the event function to obtain the source object of the event, for example, this in the click event points to the clicked element.

  • In the event function, the API provided by the applet can be called to realize corresponding functions and effects.

It should be noted that the triggering order of event functions is related to the order of binding, that is, the event function bound first is executed first. At the same time, when binding multiple event functions on an element, you need to use bindand catchto distinguish between bubbling events and non-bubbling events.

3. Two-way binding

The WeChat applet supports two-way binding by using attributes of form elements such as <input>, and so on. When the user enters content in the form element, the attribute will automatically update the bound data, and conversely, when the data is updated, the value of the form element will also be updated.<textarea>valuevalue

The following is an example that demonstrates how to implement two-way binding in a WeChat applet:

<!-- 在 wxml 文件中 -->
<view class="container">
  <input type="text" value="{
     
     {inputValue}}" bindinput="onInput" />
  <text>输入的内容是:{
   
   {inputValue}}</text>
</view>

js file

// 在 js 文件中
Page({
    
    
  data: {
    
    
    inputValue: ''
  },
  onInput: function(e) {
    
    
    this.setData({
    
    
      inputValue: e.detail.value
    })
  }
})

In this example, <input>the element's valueattribute inputValueis two-way bound to the data. When the user enters something in the input box, onInputthe method will be called setDataand inputValuethe value of the data will be updated by . During this process, valuethe properties are automatically updated to reflect the current value of inputValuethe data . At the same time, the content entered by the user will also be displayed on the page.

3. Directory structure

The directory structure of the WeChat applet is as follows:

├── app.js             // 小程序逻辑
├── app.json           // 小程序公共配置
├── app.wxss           // 小程序公共样式
├── pages              // 页面目录
│   ├── index          // index页面目录
│   │   ├── index.js   // index页面逻辑
│   │   ├── index.wxml // index页面结构
│   │   └── index.wxss // index页面样式
│   └── ...
├── components         // 组件目录
│   ├── my-component   // my-component组件目录
│   │   ├── my-component.js     // my-component组件逻辑
│   │   ├── my-component.wxml   // my-component组件结构
│   │   └── my-component.wxss   // my-component组件样式
│   └── ...
├── images             // 图片目录
├── utils              // 工具目录
├── package.json       // 项目配置文件
└── README.md          // 项目说明文件

Which states:

  • app.jsIt is the global logic file of the applet , including the lifecycle functions of the applet, etc.
  • app.jsonIt is the public configuration file of the applet , including the page path, window configuration, global style, etc. of the applet.
  • app.wxssIt is the public style file of the applet , including global style and public component style, etc.
  • pagesThe page files of the applet are stored in the directory, and each page file includes the corresponding js, wxmland wxssfiles.
  • componentsThe component files of the applet are stored in the directory, and each component file includes the corresponding js, wxmland wxssfiles.
  • imagesThe image resource files of the applet are stored in the directory.
  • utilsThe tool function file of the applet is stored in the directory, which is used to encapsulate some commonly used functions, such as request function and verification function.
  • package.jsonIt is the project configuration file of the applet, including the dependent library of the applet, the developer tool version, etc.
  • README.mdIt is the project description file of the applet, including the introduction of the applet, how to use it, frequently asked questions, etc.

Fourth, the difference between the Page constructor and the Component constructor

The basic library 1.6.3 starts to support, and the lower version needs to be compatible.

In WeChat applets, Page constructor and Component constructor are both tools used to create pages or components, but their usage and functions are different.

  • PageThe constructor is used to create a page, which is an object used to define the page's initial data, lifecycle functions, event handlers, etc. Every applet page must contain at least one Page constructor. Through the Page constructor, a new page can be created, and an existing page can be reused, so as to achieve page reuse.

  • ComponentThe constructor is used to create the component, which is also an object used to define the properties, data, methods and lifecycle functions of the component. Components are an important concept in applets, which can be referenced and reused by multiple pages. Unlike Paget, Component itself does not have a life cycle, and its life cycle is determined by the page or component that references it. The main difference with the Component constructor is that the methods need to be placed methods: { }inside .

Component code example:

Component({
    
    
  data: {
    
    
    text: "This is page data."
  },
  methods: {
    
    
    onLoad: function(options) {
    
    
      // 页面创建时执行
    },
    onPullDownRefresh: function() {
    
    
      // 下拉刷新时执行
    },
    // 事件响应函数
    viewTap: function() {
    
    
      // ...
    }
  }
})

Below I'll take a look at a simple example.

Suppose we want to create a component that contains an input box and a button. When the button is clicked, the content in the input box will be displayed on the page.

First, we can use the Component constructor to create this component, the code is as follows:

// index.wxml
<custom-input bindinput="onInput"></custom-input>

// custom-input.wxml
<view class="input-container">
  <input bindinput="onInput" placeholder="请输入内容"></input>
  <button bindtap="onTap">显示内容</button>
</view>

// custom-input.js
Component({
    
    
  methods: {
    
    
    onInput(event) {
    
    
      this.setData({
    
     value: event.detail.value })
    },
    onTap() {
    
    
      this.triggerEvent('show', {
    
     value: this.data.value })
    }
  }
})

In this example, we use the Component constructor to create a component named custom-input. This component contains an input box and a button. When the content of the input box changes, the onInput method will be triggered to save the value of the input box in the component data. When the button is clicked, the onTap method will be triggered, the custom event show will be triggered through the triggerEvent method, and the value of the input box will be passed to the event as a parameter.

Next, we can use this component in a page, the code is as follows:

// index.wxml
<custom-input bind:show="onShow"></custom-input>

// index.js
Page({
    
    
  data: {
    
    
    inputValue: ''
  },
  methods: {
    
    
    onShow(event) {
    
    
      this.setData({
    
     inputValue: event.detail.value })
    }
  }
})

In this example, we use the Page constructor to create a page named index. The page references custom-inputthe component and listens to its show event. When the event is triggered, save the value of the input box in the page data.

As you can see, the Page constructor is used to create pages, and custom components can be referenced and used in the pages. The Component constructor is used to create components that can be reused in multiple pages. This is the main difference between the two.

In general, both the Page constructor and the Component constructor are used to create different types of objects in the applet, and their functions and usage methods are slightly different. The Page constructor is used to create pages, and the Component constructor is used to create components.

5. Mini Program Life Cycle

WeChat applets have two life cycles, one is the application life cycle , and the other is the page life cycle .

1) Application life cycle

The application life cycle refers to the life cycle of the entire applet from opening to closing, including events such as the start of the applet, entering the foreground/background, and exiting. The application lifecycle of an applet includes the following events:

  • onLaunch: Triggered when the applet is initialized, it will only be triggered once.
  • onShow: Triggered when the applet starts or enters the foreground from the background.
  • onHide: Triggered when the applet enters the background from the foreground.
  • onError: Triggered when a script error or API call failure occurs in the applet.

2) Page life cycle

The page life cycle refers to the life cycle of each page in the applet, including events such as page creation, display, hiding, and destruction. Each page has its own lifecycle functions in which operations can be performed. The following diagram illustrates the lifecycle of a Page instance.
insert image description here
The following is the execution sequence of the Mini Program page lifecycle functions:

  • onLoad: Triggered when the page loads, only once.
  • onShow: Triggered when the page is displayed, and will be triggered every time the page is opened.
  • onReady: Triggered when the page is rendered for the first time, it will only be triggered once.
  • onHide: Triggered when the page is hidden.
  • onUnload: Triggered when the page is unloaded.

In addition to the above five life cycle functions, there are some other life cycle functions, such as:

  • onPullDownRefresh: Triggered when pull down to refresh.
  • onReachBottom: Triggered when the pull-up bottoms out.
  • onShareAppMessage: Triggered when the share button is clicked.
  • onPageScroll: Triggered when the page is scrolled.

It should be noted that different pages may have different life cycles, and the specific life cycle function trigger sequence and trigger times will also vary with different page types.

6. Mini Program Page Routing

The page routing of the WeChat Mini Program refers to the process of switching pages in the Mini Program. There are two ways to perform page routing in the applet:

1) Declarative navigation

<navigator>Tags can be used in applets to implement declarative navigation, similar to hyperlinks in HTML. By setting the url attribute, you can specify the page path to jump to, for example:

<navigator url="/pages/index/index">跳转到首页</navigator>

You can also specify the jump type through open-typethe attribute , for example:

  • navigateTo: Ordinary jump, close the current page and open a new page.
  • redirectTo: Redirect, close the current page and jump to the new page.
  • switchTab: Jump to the tabBar page, only jump to the page with tabBar.
  • reLaunch: Close all pages and jump to a new page.
  • navigateBack: The user presses the top left back button.

insert image description here

<navigator url="/pages/index/index" open-type="navigateTo">跳转到首页</navigator>

Precautions

  • navigateTo, redirectToonly non-tabBar pages can be opened.
  • switchTabOnly tabBar pages can be opened.
  • reLaunchAny page can be opened.
  • The tabBar at the bottom of the page is determined by the page, that is, as long as the page is defined as a tabBar, there will be a tabBar at the bottom.
  • The parameters of the calling page route can be obtained in the onLoad of the target page.

2) Programmatic navigation

Programmatic navigation can also be used in the applet for page routing by calling APIs such as wx.navigateTo(), wx.redirectTo(), wx.switchTab(), and so on. wx.reLaunch() For example:

wx.navigateTo({
    
    
  url: '/pages/index/index'
})

[Note] When using programmatic navigation in the applet, you need to declare the page path to jump to in app.jsonthe file .

{
    
    
  "pages": [
    "pages/index/index",
    "pages/about/about",
    "pages/contact/contact"
  ]
}

In the applet, you can also getCurrentPages()get all the current page stacks through API, getCurrentRoute()get the current page path through API, and monitor page route change events through onRouteChangelifecycle functions.

const pages = getCurrentPages()
const currentRoute = getCurrentRoute()

wx.onRouteChange(function(route) {
    
    
  console.log('当前路由变化为:', route)
})

7. Small program events

WeChat applets have many events that can be triggered, the following are some common events:

  • Page events : including page loading, page display, page hiding and other events;
  • View events : including click events, long press events, slide events, etc.;
  • Form events : including form submission events, form reset events, etc.;
  • Audio events : including audio playback events, audio pause events, etc.;
  • Video events : including video playback events, video pause events, etc.;
  • NavigationBar events : including navigation bar button click events, navigation bar height change events, etc.;
  • TabBar events : including Tab switching events, Tab clicked events, etc.;
  • Interaction events : including modal box display events, animation end events, etc.

The above are only part of the WeChat Mini Program events, and developers can also customize events to implement more complex interaction logic.

Below I use a simple WeChat applet example to explain event processing.

Suppose we want to implement a function now, display a button on the page, and a prompt box will pop up after clicking the button, and a text content will be displayed on the prompt box.

1. Add a button element to the WXML file:

<view>
  <button bindtap="showModal">点击我</button>
</view>

Here we use <button>the element to create a button, which has an bindtapattribute, which is used to bind tap the event , and call showModalthe function to handle the event.

2. Add showModalthe function :

Page({
    
    
  showModal: function() {
    
    
    wx.showModal({
    
    
      title: '提示',
      content: 'Hello, world!'
    })
  }
})

Here we use wx.showModalthe function to create a prompt box, which has two parameters: titleand content, which are used to set the title and content of the prompt box respectively. In the showModal function, we directly call wx.showModalthe function and pass in the corresponding parameters.

3. Preview the page in the WeChat developer tools, click the button, and you can see the pop-up prompt box, which shows the text content of Hello, world!

The above is a simple WeChat applet event processing example. By binding the tap event and calling the corresponding function to handle the event, the function of popping up the prompt box after the button is clicked is realized. Developers can write corresponding event processing functions according to their own needs to achieve more complex interaction effects.

It’s a bit long, so I’ll stop here first, and the rest of the content will be put into the next article to continue explaining. If you have any questions, please leave me a message. You can also follow my public account [Big Data and Cloud Native Technology Sharing] and join the group exchange Or private message communication~

Guess you like

Origin blog.csdn.net/qq_35745940/article/details/130045406