Wechat applet entry must see ①

preface

We use wechat for communication and payment. The rapid rise of small programs relying on wechat is considerable. Today, we will start from the most basic to understand the composition of the applet step by step. Let's write our first wechat applet together~

1, Host environment

1. What is the host environment?

Host environment refers to the dependent environment necessary for program operation, such as:

  1. Android system and IOS system are two different host environments
  2. Android version of wechat App cannot run in IOS environment. Therefore, Android is the host environment of Android Software, and software separated from the host environment is meaningless

2. Hosting environment of applet

Mobile wechat is the host environment of the applet, as shown in the figure:

With the help of the capabilities provided by the host environment, applets can complete many functions that ordinary web pages cannot complete, such as:

Wechat code scanning, wechat payment, wechat login, geographic location, ETC, ETC

  • Content contained in the applet hosting environment
    • communication model
    • operating mechanism
    • assembly
    • API

3. Communication subject of applet

The main body of communication in the applet is the rendering layer and the logic layer, where:

  1. WXML templates and WXSS styles work on the render layer
  2. JS scripts work at the logical level

4. Communication model of applet

The communication model in the applet is divided into two parts

  1. Communication between render layer and logical layer
    Forwarded by wechat client

  2. Communication between logical layer and third-party server
    Forwarded by wechat client

5. Operation mechanism

  • Applet startup process
    • Download the applet's code package locally - get the code package from the cache
    • Parsing app.json global configuration file
    • Execute the app.js applet entry file and call App() to create an applet instance
    • Rendering applet home page
    • Applet start complete

  • The process of page rendering
    • Load the. json configuration file that parses the page
    • Load the. wxml template and. wxss style for the page
    • Execute the. js file of the page and call Page() to create a page instance
    • Page rendering complete

2, Components in applets

1. Common view components

  • The components in the applet are also provided by the host environment. Developers can quickly build a beautiful page structure based on the components. Officially, the components of small programs are divided into 9 categories:
    ① View container ② basic content ③ form component ④ navigation component ⑤ media component
    ⑥ map component ⑦ canvas component ⑧ development capability ⑨ barrier free access

  • Common view container class components

    • view component
      Normal view area, similar to div in HTML
      Is a block level element
      Commonly used to achieve the layout effect of the page

    • Scroll view component
      Scrollable view area
      Commonly used to achieve the effect of scrolling list

    • Wiper and wiper item components
      Carousel chart container component and carousel chart item component

2. view component

Equivalent to div in HTML

Easy to use:
The code is as follows (example):
Write structure code in. wxml

<view class="container">
  <view>A</view>
  <view>B</view>
  <view>C</view>
</view>

Write style code in. wxss

.container {
  display: flex;
  justify-content: space-around;
}
.container view{
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.container view:nth-child(1) {
  background-color: lightgreen;
}

.container view:nth-child(2) {
  background-color: lightskyblue;
}

.container view:nth-child(3) {
  background-color: lightcoral;
}

3. Sroll view component

Application scenario: common left menu bar / right commodity sliding effect in takeout applet

Easy to use:
The code is as follows (example):
Writing structure code in wxml

<!-- scroll-x Properties: allow horizontal scrolling -->
<!-- scroll-y Properties: allow vertical scrolling -->
<!-- Note: when using vertical scrolling, you must scroll-view A fixed height -->
<scroll-view class="container" scroll-y>
  <view>A</view>
  <view>B</view>
  <view>C</view>
</scroll-view>

Writing style codes in wxss

.container {
  width: 100px;
  height: 120px;
}

.container view{
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.container view:nth-child(1) {
  background-color: lightgreen;
}

.container view:nth-child(2) {
  background-color: lightskyblue;
}

.container view:nth-child(3) {
  background-color: lightcoral;
}

4. Carousel chart assembly

The applet integrates the label swiper of the effect of the rotation picture, but the swiper label needs to be used with the swiper item label. There are also many practical properties. Please see the code below~

Easy to use:
The code is as follows (example):
Writing structure code in wxml

<!-- Rotation map area -->
<!-- indicator-dots Properties: display panel indicator points -->
<swiper indicator-dots class="swiper-container">
  <!-- First item -->
  <swiper-item>
    <view class="item">A</view>
  </swiper-item>
  <!-- Item 2 -->
  <swiper-item>
    <view class="item">B</view>
  </swiper-item>
  <!-- Item 3 -->
  <swiper-item>
    <view class="item">C</view>
  </swiper-item>
</swiper>

Writing style codes in wxss

.swiper-container {
  /* Height of carousel container */
  height: 150px;
}

.item{
  height: 100%;
  line-height: 150px;
  text-align: center;
}

swiper-item:nth-child(1) .item{
  background-color: lightgreen;
}

swiper-item:nth-child(2) .item{
  background-color: lightskyblue;
}

swiper-item:nth-child(3) .item{
  background-color: lightcoral;
}

Quick query table of common attributes
Common property documents of the wiper component

attributetypeDefault valueexplain
indicator-dotsbooleanfalseDisplay panel indicator points
indicator-colorcolorrgba(0, 0, 0, .3)Indicates the point color
indicator-active-colorcolor#000000The color of the currently selected indicator point
autoplaybooleanfalseWhether to switch automatically
intervalnumber5000Automatic switching interval
circularbooleanfalseWhether connection sliding is adopted

5. Text component

There are two common text components:

  • text
    Text component
    Similar to the span tag in HTML, it is an inline element

  • rich-text
    Rich text component
    Supports rendering HTML strings to WXML structures

Textcomponent easy to use:
Through the selectable attribute of the text component, the effect of long pressing the selected text content is realized

<!-- Common basic content components text and rich-text Usage of -->
<view>
  The mobile phone number supports the long press selection effect
  <text selectable>18222222222</text>
</view>

Basic usage of rich text component:
Render the HTML string as the corresponding UI structure through the nodes attribute node of the rich text component

<!-- Application scenario -->
<rich-text nodes="<h4 style='color: red'>rich-text assembly</h4>"></rich-text>

6. Button assembly

It is the same as the button tag in HTML, but the button component in the applet is more functional.

Other common components

  • button
    Button assembly
    Through the open type attribute, you can call various functions provided by wechat (customer service, forwarding, obtaining user authorization, obtaining user information, etc.)

  • image
    Picture component
    The default width of the image component is about 300px and the height is 240px

  • navigator
    Page navigation component
    Similar to the a tag in HTML

Quick look-up table of common attributes of button components
Detailed documentation of the Button component

Attribute nametypeDefault valueexplain
sizeStringdefaultButton size
typeStringdefaultThe style type of the button
plainBooleanfalseWhether the button is hollow and the background color is transparent
disabledBooleanfalseDisable
loadingBooleanfalseDoes the name have a loading t icon

Button components are easy to use:

<!-- adopt type Specify button type -->
<button>Default button</button>
<button type="primary">Main tone button</button>
<button type="warn">Warning button</button>


<!-- size="mini" Small size button -->
<button size="mini">Default button</button>
<button size="mini" type="primary">Main tone button</button>
<button size="mini" type="warn">Warning button</button>

<!-- plain Hollowed out effect -->
<button plain size="mini">Default button</button>
<button plain size="mini" type="primary">Main tone button</button>
<button plain size="mini" type="warn">Warning button</button>

7. Picture component

The picture tag in the applet is image and img in HTML

image components are easy to use

  • src – support local and network pictures
  • Mode – specifies the cropping and scaling mode of the picture
<!-- 2. use src Point to picture path -->
<image src="/images/xxx.jpg" mode="widthFix"></image>

Common attribute values of mode attribute of picture component

mode valueexplain
scaleToFillThe default value, zoom mode, does not maintain the aspect ratio to scale the picture, so that the width and height of the picture are fully stretched to fill the image element
aspectFitZoom mode, keep the aspect ratio to zoom the picture, so that the long edge of the picture can be fully displayed. In other words, the picture can be displayed completely.
aspectFillZoom mode, keep the aspect ratio to zoom the picture, and only ensure that the short edge of the picture can be fully displayed. In other words, the picture is usually complete only in the horizontal or vertical direction, and will be intercepted in the other direction.
widthFixIn zoom mode, the width remains unchanged and the height changes automatically. The width here refers to the image width and is no longer the default value
heightFixIn zoom mode, the height remains unchanged and the width automatically changes, keeping the width height ratio of the original image unchanged. Here, the height refers to the image height and is no longer the default value

3, Data binding

1. Data binding principle

Similar to vue, the basic principles of applet data binding are:

  • Define data in data
  • Using data in wxml

Definition: the data required by the page can be defined in the data object in the js file corresponding to the page.

data: {
  num: 0
}

Usage: in wxml, wrap variables in Mustache syntax (double braces)

<view>{{ num }}</view>

2. Dynamic binding attribute

Application scenario of Mustache syntax:

  • Binding content
  • Binding properties
  • Operation (ternary operation, arithmetic operator)

If you already know vue, it can be understood that it can be written in vue's interpolation expression and Mustache grammar.

4, Event binding

In small programs, the binding of events is different from vue.

1. What is an event

Events are the means of communication from the render layer to the logical layer. Through events, the user's behavior in rendering can be fed back to the logic layer for business processing

2. Common events

  • bindtap,bindinput,bindchange

  • bind:tap,bind:input,bind:chage

    typeBinding modeEvent description
    tapbindtap or bind:tapThe finger leaves immediately after touching, which is similar to the click event in HTML
    inputbindinput or bind:inputInput event for text box
    changebindchange or bind:changeTriggered when the status changes

List of properties for the event object
When the event callback is triggered, an event object event will be received. Its detailed properties are as follows

attributetypeexplain
typeStringEvent type
timeStampIntegerTimestamp when the event was generated
targetObjectA collection of property values of the component that triggered the event
currentTargetObjectA collection of property values for the current component
detailObjectAdditional information
touchesArrayTouch event, an array of touch point information currently staying on the screen
changedTouchesArrayTouch event, an array of currently changing touch point information

3. Difference between target and currentTarget

  • target is the source component that triggers the event
  • currentTarget is the component bound by the current event

When you click an internal button, the click event spreads outward in a bubbling manner, which will also trigger the tap event handler of the outer view
At this time, for the view of the outer layer:

  • e. Target specifies the source component that triggers the event, because e.target is an internal button component
  • e. Currenttarget refers to the component that is currently triggering the event, so e.currentTarget is the current view component

4. bindTab

In the applet, there is no onclick mouse click event in HTML, but the tap event is used to respond to the user's touch behavior

  • With bindtap, you can bind tap touch events to components
  • The corresponding event handling function is defined in the. js file of the page, and the event parameters are received through the formal parameter event (generally abbreviated as e)

Example code:

data: {
  count: 0
}
// Button tap event handler
btnTapHandle (e) {
  // Event parameter object e
  console.log(e)
  // You can use setData to assign values to the data in data
  // The parameters passed to the event handler can be obtained from the dataset in the event object e
  this.setData({
  	count: this.data.count + e.target.dataset.num
  })
}

wxml code

<view>
  <button type="primary" data-num="{{ 2 }}" bindtap="btnTapHandle">+2</button>
</view>

5. bindinput

Bind an input event to the input box. Here we mainly realize the two-way binding of text box and data data.

Sample code (as follows):
wxml writing structure code

<view>
  <input value="{{ msg }}" bindinput="setMsg" />
</view>

Write the logic code in the corresponding js file

data: {
  msg: ``
},
// Realize data synchronization between text box and data
setMsg (e) {
  this.setData({
    msg: e.detail.value
  })
}

Writing style codes in wxss

input {
 border: 1px solid lightcoral;
  padding: 5px;
  margin: 5px;
  border-radius: 3px;
}

5, Conditional rendering

The conditional rendering statements used in vue are v-if and v-show, which are similar to wx:if in applets. They are usually used with wx:elif and wx:else

1. wx:if

Sample code (as follows):

<!-- conditional rendering  -->
<view wx:if="{{ type === 1 }}">male</view>
<view wx:elif="{{ type === 2 }}">female</view>
<view wx:else>secrecy</view>

If you want to perform conditional judgment rendering on a whole, and do not want to use the view component to increase the nesting of useless tags, you can use the block tag, which is similar to the template in vue. It can complete conditional judgment and will not be rendered to the page.

2. hidden

In the applet framework, directly using hidden = "{condition}}" can also control the display and hiding of elements

Sample code (as follows):

<view hidden="{{ false }}">Condition is true Hidden if false display</view>

3. Difference between Wx: if and hidden

Different operation modes

  • wx:if controls the display and hiding of elements by dynamically creating and removing elements

  • hidden controls the display and hiding of elements by switching styles (display: none/block)

Use suggestions

  • hidden is recommended when switching frequently
  • When the control conditions are complex, it is recommended to use wx:if with wx:elif and wx:else to switch between display and hiding

6, List rendering

1. wx:for

With wx:for, you can render repeated component structures in a loop according to the specified array.
When rendering: directly put the variable name in data in double curly braces
The default item is each item in the data, and index is the index of each item

Sample code (as follows):
Define an array in the data object of the js file

data: {
  arr: ['Arthur', 'Daji', 'Meng Tian']
}

Rendering array data in wxml

<view wx:for="{{ arr }}">
  Index is: {{ index }},Each item of the array is:{{ item }}
</view>

2. Modify default

Use Wx: for item to specify the variable name of the current element of the array
Use Wx: for index to specify the variable name of the current subscript of the array

<view wx:for="{{ arr }}" wx:for-index="idx" wx:for-item="itemName">
  Index is: {{ idx }},Each item of the array is:{{ itemName }}
</view>

3. wx:key

Similar to the: key in Vue list rendering, when the applet implements list rendering, it is also recommended to specify a unique key value for the rendered list items, so as to increase the rendering efficiency

summary

A good book is your best friend.

Tags: Front-end Mini Program

Posted on Thu, 14 Oct 2021 14:06:51 -0400 by rashpal