1. WeChat Mini Program - Environment Construction, Basic Grammar


foreword

This chapter introduces the installation of applets, environment construction and project directory.


1. Introduction to WeChat Mini Programs

1. WeChat Mini Program

Mini Program for short, English name Mini Program, is an application that can be used without downloading and installing. Opening the application has the following advantages:

  1. WeChat has a large number of users, and the stickiness is very high. It is easier to reach users when developing products in WeChat;
  2. The cost of promoting an app or official account is too high.
  3. The cost of development and adaptation is low.
  4. It is easy to trial and error on a small scale, and then iterate quickly.
  5. Cross-platform.

2. Operating environment

The host environment of the Mini Program: We call the environment provided by the WeChat client to the Mini Program as the host environment. With the help of the capabilities provided by the host environment, applets can accomplish many functions that ordinary web pages cannot. The running environment of the applet is divided into a rendering layer and a logic layer, where WXML templates and WXSS styles work on the rendering layer, and JS scripts work on the logic layer.

The rendering layer and logic layer of the applet are managed by two threads respectively: the interface of the rendering layer uses WebView for rendering; the logic layer uses JsCore thread to run JS scripts. There are multiple interfaces in a small program, so there are multiple WebView threads in the rendering layer. The communication between these two threads will be relayed through the WeChat client (Native will also be used to refer to the WeChat client below), and the logic layer will send network requests. It is also forwarded by Native, and the communication model of the applet is shown in the figure below.
insert image description here

3. Environment preparation

For specific steps, please refer to:
WeChat Mini Program Development Document: https://developers.weixin.qq.com/miniprogram/dev/framework/quickstart/getstart.html

1) Apply for an account
Enter the mini program registration page and fill in the information and submit the corresponding materials according to the guidelines, and you can have your own mini program account. After successful registration, you can log in and get the APPID. You can also use the test account without registration, but you need to ask for the APPID in the developer's applet to log in to call the interface, payment and other functions of the WeChat applet later.
2) Install development tools
Go to the developer tools download page, download the corresponding installation package according to your own operating system and install it.
3) Create a new project
insert image description here
and fill in the project information
insert image description here

Create a new project and select the applet project, select the hard disk path where the code is stored, fill in the AppID of the applet you just applied for, give your project a name, and check "Do not use cloud services" (Note: You need to choose an empty directory, you can create a project), click New, and you will get your first applet, and click Compile on the top menu to preview your first applet in the WeChat developer tools.

Open the compiler and you can see the working interface of the WeChat developer tool as follows:
insert image description here

2. The directory structure of the project

1. Small program project structure compared with traditional web

The applet framework provides its own view layer description languages ​​WXML and WXSS, as well as JavaScript, and provides data transmission and event systems between the view layer and logic layer, allowing developers to focus on data and logic.
insert image description here
Through the above comparison, it can be concluded that the traditional web has a three-tier structure. The WeChat applet has a four-layer structure, with an additional layer of .json configuration files.

2. The basic directory structure of the applet

insert image description here
Different types of files are generated in the project:

2.1 .json configuration file

The applet global configuration app.json includes all page paths, interface performance, network timeout, bottom tab, etc. of the applet:

{
    
    
"pages":[
"pages/index/index",
"pages/logs/logs"
],
"window":{
    
    
"backgroundTextStyle" : "light",
"navigationBarBackgroundColor" :  "#fff",
"navigationBarTitleText" :  "WeChat",
"navigationBarTextStyle" : "black"
}
}

Meaning of the fields:

  1. The pages field is used to describe the path of all pages of the current Mini Program, which is to let the WeChat client know which directory your Mini Program page is currently defined in.
  2. The window field defines the top background color of all pages of the applet, text color definition, etc.
  3. For complete configuration information, please refer to app.json configuration

The tool configuration project.config.json is a personalized configuration when developing a project, which will include a series of options such as the color of the editor, automatic compression when the code is uploaded, and so on.
The page configuration page.json allows developers to independently define some properties of each page, such as the top color just mentioned, whether to allow pull-down refresh, and so on.
sitemap.json is used to configure whether the Mini Program and its pages are allowed to be indexed by WeChat.

Before introducing the basic grammar of applets, we need to know briefly:
Those who have been engaged in web programming know that web programming uses a combination of HTML + CSS + JS, where HTML is used to describe the structure of the current page, and CSS is used to Describe the appearance of the page, and JS is usually used to handle the interaction between the page and the user. Among them, WXML plays a role similar to HTML. WXSS is CSS. JS still handles the logic.
The tags used in the WXML of the applet are view, button, text, etc. These tags are the basic capabilities packaged by the applet for developers. We also provide map, video, audio and other component capabilities.
The framework used by the applet is called MINA. The idea of ​​framework construction: adopt the development mode of MVVM (such as React, Vue), and advocate the separation of rendering and logic. To put it simply, do not let JS directly manipulate the DOM, JS only needs to manage the state, and then use a template syntax to describe the relationship between the state and the interface structure.

2.1 Template syntax (see demo01 for the code)

WXML (WeiXin Markup Language) is a set of labeling languages ​​designed by the framework. Combining basic components and event systems, the structure of the page can be constructed.
1. Data binding
writing method:

<view>  {
    
    {
    
      message  }}  </view>
Page({
    
    
data :  {
    
    
message :  'Hello  MINA!'
}
})

2. Component properties

<view  id="item-{
    
    {id}}">  </view>
Page({
    
    
	data :  {
    
    
	   id : 0
	}
})

insert image description here

3.
Do not directly write checked="false" for boolean, the calculation result is a string

<checkbox  checked= "{
    
    {false}}">  </checkbox>

4. Operation
Ternary operation:

<view  hidden= "{
    
    {flag  ?  true  :  false}}">  Hidden  </view>

Arithmetic operations:

<view>  {
    
    {
    
    a  +  b}}  +  {
    
    {
    
    c}}  +  d  </view>

String operations:

<view>{
    
    {
    
    "hello"  +  name}}</view>
Page({
    
    
data:{
    
    
name :  'MINA'
}
})

Note: If there is a space between curly braces and quotation marks, it will eventually be parsed into a string

5.
The variable name of the list rendering item is item wx by default. :for-item can specify the variable name of the current element of the array. The
subscript variable name defaults to index wx. :for-index can specify the variable name of the current subscript of the array
wx. High array rendering performance, wx : key binding value has the following choices
1) string type, which means the only attribute in the loop item

list:[{
    
    id:0,name:"炒饭"},{
    
    id:1,name:"炒面"}]
wx:key= "id"

2) The reserved word *this means the item itself, and *this must represent unique strings and arrays.
The complete usage code is as follows:

list:[1,2,3,4,5]
wx:key= "*this"

The complete usage code is as follows:

<view  wx:for= "{
    
    {array}}"  wx:key= "id">
{
    
    {
    
    index}}:  {
    
    {
    
    item.message}}
</view>
Page({
    
    
data :  {
    
    
array :  [{
    
    
id :0,
message :  'foo',
},  {
    
    
id :1,
message :  'bar'
}]
}
})

6. Block
renders a structural block containing multiple nodes. Block will not become a real DOM element in the end.

<block  wx:for= "{
    
    {[1,  2,  3]}}"  wx:key= "*this"  >
<view>  {
    
    {
    
    index}}:  </view>
<view>  {
    
    {
    
    item}}  </view>
</block>

What is DOM under the extension here?
The DOM is the Document Object Model (Document Object Model) that the browser creates when a web page is loaded. After the browser receives the code, it parses it. After three steps: DOM construction, layout, and page drawing, it finally presents a web page that everyone can understand.
insert image description here

The browser first parses the received html code into a DOM tree through the html parser. The DOM tree is like a big tree that grows upside down. Such an object model determines that there is a certain relationship between nodes. Their relationship may include father and son, and brothers. We can perform many operations along this tree. Then, the received css code is used to construct the style sheet rules through the css parser, and these rules are respectively placed on the corresponding DOM tree nodes to obtain a DOM tree with style attributes.

The browser reads the document nodes of the DOM tree in order from top to bottom and from left to right, and stores them sequentially on a virtual conveyor belt. The boxes on the conveyor belt are the nodes, and this flowing conveyor belt is the document flow. After the document stream is arranged, it starts to obtain CSS properties such as coordinates and sizes of calculation nodes, and then arranges the nodes one by one, which layouts the nodes on the page.

After the layout is completed, we can't actually see any content on the page. The browser just calculates where each node object should be placed on the page, but it doesn't visualize it. So the last step is to draw all the content and complete the rendering of the entire page.

7. Conditional rendering
Wx:if
In the frame, use wx :if="{ {condition}}" to determine whether the code block needs to be rendered:

<view  wx:if= "{
    
    {false}}">1</view>
<view  wx:elif= "{
    
    {true}}">2</view>
<view  wx:else>3</view>

Hidden

<view  hidden= "{
    
    {condition}}">  True  </view>

Note: Similar to wx:if, if you switch frequently, it is recommended to use hidden

8. Event binding (see demo02 for the code)
Binding events in the applet is realized through the bind keyword. Different components such as bindtap bindinput bindchange support different events, please refer to the description of the components for details.
Example use:
add the following code in wxml, and bind a handleInput event to the input tag

<input  bindinput= "handleInput"  />

Define this event in the js file

Page({
    
    
//  绑定的事件
handleInput :  function(e)  {
    
    
console .log(e);
console .log("值被改变了");
}
})

It should be noted that when binding events, parameters cannot be used and parentheses are not allowed. The following are incorrect usages

<input  bindinput= "handleInput(100)"  />

The correct way to pass the value of the event should be, the way and value of the custom attribute through the label

<input  bindinput= "handleInput"  data-item= "100"  />

2.2. WXSS style file with wxss suffix (see demo03 for code)

Let's get to know css first:
1. Definition: CSS is usually called CSS style or cascading style sheet, which is mainly used to set the text content (font, size, alignment method, etc.) in HTML pages. When using HTML, you need to follow certain norms, and CSS also has certain norms

选择器{
    
    
		属性1:属性值;
		属性2:属性值;
}

2. The "selector" is used to specify the HTML object of the CSS style effect. The specific style attributes and attribute values ​​set for the object are presented in the form of key-value pairs in the brackets. The English colon ":" separates multiple attributes using English points Number";". It should be noted that
"selector" is strictly case-sensitive, and "attribute" and "attribute value" are not case-sensitive.
3. The style uses
inline style: the style of the element is set through the style attribute of the label, and the inline style is passed through the label. Attributes to control styles, without separation of structure and performance (HTML structure, CSS display) (use less)

<a style="color:#000;font-size:30px;"></a>

Internal styles: The CSS code is centrally unloaded in the tag body of the HTML document, and uses

<head>
	<style>
		body{
    
    
		height:100px;
		}
	</style>
</head>

External styles: External styles are also called link-in, put all styles in one or more external style sheet files, and put all styles in one or more external style sheet files

<link rel="stylesheet" type="text/css" href="css/style.css">

Priority: inline style > internal style (embedded) > external style

4. Use of selectors
1) Default style: * This symbol can match all styles, so if there is no additional definition, it will default to this style. It is generally used to eliminate the inner and outer margins between the page and the browser

<style>
    *{
    
    
        padding:0;  // 所有标签默认消除内边距
        margin:0;  // 所有标签默认消除外边距
    }
</style>

2) Tag selector, the example is to match all span tags and set their css style

<style>
        span{
    
    
            font-size:26px;  // 设置所有span里字体大小
            color:snow;  // 设置span里的字体颜色
        }
    </style>

3) The class selector, the example is to match all the tags with class='bgcolor', and set the style. Note that there is a point in English in front of the style

<style>
    .bgcolor{
    
    
        font-size:26px;  // 设置字体大小
        color:snow;  // 设置字体颜色
        background:pink; // 设置背景颜色
    }
</style>

4) id selector, the example is to match the label with id='yun', and set its css style. It should be noted that the value of id must be unique in the entire html page, that is, duplicate ids cannot appear in different labels value

    <span id='yun'>i want you</span>
    <p id='yun'>i miss you</p>  // 此标签为错误示例,因为id和上面的重复了!

<style>
    #yun{
    
    
        font-size:26px;  // 设置字体大小
        color:snow;  // 设置字体颜色
    } 
    // 另外不要纠结这个样式,#yun 能不能重复写,能重复写,但是你都能重复写了,为什么不把样式写在一起?
</style>

5) Multi-element selectors, separated by commas, such as selection, tags with id=yun and class='abc', apply styles

<style>
    #yun,.abc{
    
    
        font-size:26px;  // 设置字体大小
        color:snow;  // 设置字体颜色
    }

    // 或者
    span,#yun,.abc,.cde{
    
    
        color:green; 
    } 
</style>

6) Descendant selectors, separated by spaces

 <div id='yun'>
        <p>会被应用样式</p>
        <div>
            <p>这个也会被应用</p>
        </div>
    </div>
    <style>
        // 该样式会应用于,id为yun标签下面的p标签,注意这里指的是下面所有,包括子元素,子元素的子元素,子子子元素... 只要是p标签
        #yun p{
    
    
            font-size:26px;  // 设置字体大小
            color:snow;  // 设置字体颜色
        } 
    </style>

7) Child element selector, use the > symbol

 <div id='yun'>
        <p>仅这样的子元素会被应用样式</p>
    </div>
    <style>
        // 该样式会应用于id为yun这个标签下面的p标签子元素,
        #yun>p{
    
    
            font-size:26px;  // 设置字体大小
            color:snow;  // 设置字体颜色
        } 
    </style>

5. The priority of the selector The
priority of the wildcard selector, selector and logical combination pseudo-class is 0.
Label selectors have a priority of 1.
Class selectors, attribute selectors, and pseudo-classes have a priority of 2.
The ID selector has a priority of 3.
The priority of the style attribute inline style is 4.
!important priority is the highest, which is 5.

Calculation rules:
The selector of each CSS statement can correspond to a specific value. The larger the value, the higher the priority, and the CSS statement in it will be rendered first. The specific rules are:
when a level 0 selector appears, the priority value +0;
when a level 1 selector appears, the priority value +1;
when a level 2 selector appears, the priority value +10;
when a level 3 selector appears, Priority value +100.

The following examples will help you better understand how the priority of selectors is determined:
insert image description here
WXSS (WeiXin Style Sheets) is a set of style languages ​​used to describe WXML component styles . Compared with , extended features are:

  • Responsive length unit rpx

  • style import

WXSS supports the new size unit rpx at the bottom layer. Developers can avoid the trouble of conversion. They just need to hand it over to the bottom layer of the applet for conversion. Since the conversion uses floating-point calculations, the calculation results will be slightly different from the expected results. You can write an app.wxss as a global style, which will be applied to all pages of the current applet, and a local page style page.wxss will only take effect on the current page.
1. The use of rpx (responsive pixel)
can be adapted according to the screen width. The specified screen width is 750rpx. For example, on iPhone6, the screen width is 375px, and there are 750 physical pixels in total, then
750rpx = 375px = 750 physical pixels,
1rpx = 0.5px = 1 physical pixel.

insert image description here
Designers can use iPhone6 ​​as the standard for visual drafts when developing WeChat applets. Steps to use:

  1. Determine the design draft width pageWidth
  2. The calculation ratio is 750rpx = pageWidth px, so 1px=750rpx/pageWidth.
  3. In the less file, just set px => 750/pageWidth rpx in the design draft.

2. Import style
1) Internal style

/**  common.wxss  **/
.small-p  {
    
    
padding :5px;
}

2) External styles

/**  app.wxss  **/
@import  "common.wxss";
.middle-p  {
    
    
padding :15px;
}

Note: Special attention should be paid to the fact that the applet does not support wildcards *, so the following code is invalid!

3) Supported style selectors
insert image description here

2.3 JS script logic files with .js suffix

It is not enough for a service to only display the interface, it also needs to interact with the user: respond to the user's click, obtain the user's location, and so on. In the applet, we handle user operations by writing JS script files.


Guess you like

Origin blog.csdn.net/qq_40348833/article/details/124248073