WeChat mini-app experience, trust mini-app experience

Source: Internet
Author: User
Tags openscad

Tips on small programs

First, let's start with the framework provided in the official documents. The official documents of applets provide the app. js, app. json, app. wxss. start with these three files. -app. the js file is the entrance file of the entire applet. the developer's logic code is implemented here, and global variables can be defined in this folder. -app. the json file can be configured globally for the applet to determine the path and window performance of the page file, set the network timeout time, and set multiple tabs. -app. wxss is a small program's public style table. (to adapt to the majority of front-end developers, our WXSS has most of the CSS features. At the same time, we have expanded and modified CSS to make it more suitable for developing small programs .)

Next, let's take a look at the three files mentioned above based on the official code.

Window

This configuration item is used to set the status bar, navigation bar, title, and window background color of the applet. He provides six attributes (NavigationBarBackgroundColor (HexColor), navigationBarTextStyle (String-(black, white), navigationBarTitleText (String), backgroundColor (HexColor), backgroundTextStyle (String-(dark, light )), enablePullDownRefresh (Boolean)), Developers can configure according to their own needs.
The functions of these attributes are described in detail:

  • NavigationBarBackgroundColorThis attribute is used to set the background color of the navigation bar.Hexadecimal color value.
  • NavigationBarTextStyleIt is used for the title Color of the navigation bar, and its input type is String, but the documents provided on the official website currently only support the two colors (black and white.
  • NavigationBarTitleTextThis attribute displays the title of the navigation bar. developers can set this attribute based on their own needs .-BackgroundColorThis attribute is used to set the background color of the window.Hexadecimal color value.
  • BackgroundTextStyleThis attribute is used to set the style of the window content. The official standard description is the drop-down background font and loading graph style. This attribute is the same as the navigationBarTextStyle attribute currently.Only supportedTwo colors (dark and light ).
  • EnablePullDownRefreshThis attribute is setWhether to enable pull-down refreshIs enabled by default,Note:In this configuration file (app. if the pull-down refresh function is disabled, it will not work if you want to set the pull-down refresh function on your own page. That is to say, if you want to use the pull-down refresh function in future pages, make sure that this setting in this configuration file is enabled.
    The sample code shown above:
    {"Window": {"navigationBarBackgroundColor": "# ffffff", "navigationBarTextStyle": "black", "navigationBarTitleText": "interface function demonstration", "backgroundColor ": "# eeeeee", "backgroundTextStyle": "light "}}

     

     
    The result is as follows:

Write the image description tabBar here.

This configuration item is used to configure the tab bar at the bottom of the page. developers can configure it as needed.

Note:TabBar isArray, Can only be configuredAt least 2,Up to 5And the order of the tab column is sorted by array.

TabBar provides the following five attributes (Color (HexColor), selectedColor (HexColor), backgroundColor (HexColor), borderStyle (String), list (Array)).

Next let's talk about my understanding of these five attributes:

  • ColorSet the default color of text on the tab
  • SelectedColorSet the color of the selected text on the tab
  • BackgroundColorSet the tab background color
  • BorderStyleSet the border color. Currently, only black and white are supported)
    The above four attributes can be set according to the official API. The following describes the list attribute. the list attribute accepts an Array, and each item configured under the list is an object. They all have the following four attributes (PagePath (String), text (String), iconPath (String), selectedIconPath (String)).
    PagePathThis defines the page path, but the path defined by this attribute must be defined on pages.
    TextSet text on the button
    IconPathDefine the path of the icon image. The image size defined by this attribute cannot exceed 40kb.SelectedIconPathIt defines the image displayed after the button is selected. The size of the same image cannot exceed 40kb.
    The following is officially provided:


    Applet
NetworkTimeout

It is used to set the timeout time for various network requests. The unit is millisecond. The official website provides four attributes (Request, connectSocket, uploadFile, downloadFile) Which of the following attributes are defined respectively?Wx. request, wx. connectSocket, wx. uploadFile, downloadFileThe timeout time of the four APIs.

Debug

If debug is set to true in app. json, detailed debugging information can be output in the console Panel of the developer tool.
The above is based on the official documents. After learning about app. json configuration, let's take a look at the app. js file.

You can see the app. the suffix of the js file is JavaScript. That's right. The language used by the development framework of the applet in the logic layer is JavaScript. but the applet also makes a modification based on JavaScript, which can be called a new wheel. this framework makes it easier for developers to call some features, such as scan and payment.

Let's go back to the app. js file. Let's talk about it later.

This file is the entrance file of the entire applet, or the file that controls the lifecycle of the entire applet. It is not hard to imagine the functions we should implement in this file, first, we certainly need to register the entire program, just to provide us withApp ()To register the entire program. At the same time, the app () also implements the monitoring function for the life cycle of the applet (OnLaunch, onShow, onHide), Where onLaunch is listening for applet initialization. When Initialization is complete, onLaunch is triggered. Of course, this function is only triggered once globally. onShow is used to monitor the display of applets. This function is triggered when the applet is started or when you enter the foreground from the background. the onHide function is used to listen for hidden small programs. When you switch from the front-end to the background, onHide is triggered. with these small programs, the instances are basically completed. Of course, to allow developers to add more logic, developers can also add their own logic to the app, developers can add any function or data to the Object parameters.ThisAccessible.

Note: The app () can only be defined in app. js and cannot register multiple.

When. after registering an instance in js, if you want to call it on your own logic page, you can use the getApp () global function so that you can call the app () globally () data.

The official code is as follows:

var appInstance = getApp()console.log(appInstance.globalData) // I am global data

Note: Do not call the lifecycle function without permission after getApp () obtains the instance. and do not go to the app. using the getApp () function in js, you can use this to call things in app.

Basically, app. js will introduce these things in some APIs in the future. next let's take a look at the app. wxss files have been developed on websites in general (I developed them using php myself. This is my personal opinion. If there is any mistake, please forgive me) I believe that css should be written in a separate file, this app. wxss is similar, but its configuration is global. That is to say, if you do not reconfigure it in the following page, it will call the style settings in this file, however, if you need to rewrite the style on each page, it does not matter. It will automatically overwrite the style in the cut file.

When you re-create a small program, these files will appear. The above is my understanding of them in combination with the official documentation. The next step is the page logic, view, and configuration experience.

Page

This is the developer's own business implementation file. every page can be placed in a folder, which generally includes. js ,. json ,. wxml ,. for the four wxss files, it is recommended that the names of the four files be the same as those of the folder. this facilitates automatic search by the framework and requires no more configuration.

When you start the page function. js also needs to be registered. The official website provides the Page () function to register a Page. It accepts an object parameter and uses it to specify the initial data and lifecycle function of the Page, event processing functions. it should be noted that when you register this page, you must determine the app at the beginning. this page has been configured in the json configuration file, and when you change the program, make sure the app. the content in the json file is also changed accordingly.

For the Page () function, perform the following operations (Data (Object), onLoad (function), onReady (Function), onShow (Function), onHide (Function), onUpload (Function), onPullDownRefresh (Function)), And you can also add any function or data to the object parameter. on this page, use this to access.

The following briefly introduces the official attributes:

  • Data-implement page initialization data
  • OnLoad is a lifecycle function used to listen for page loading. A page is called only once. Its parameters can be used to obtain the query in wx. navigateTo, wx. redirectTo, and <navigator/>.
  • OnReady-the same life cycle function is used to listen to the first page rendering. A page is called only once, indicating that the page has been properly prepared and can interact with the view layer. set the page after onReady, for example, wx. setNavigationBarTitle.
  • OnShow-Life Cycle Function, used to listen to page display. It is called every time the page is opened.
  • OnHide-life cycle function, which hides ''on the listener page. It is called after wx. navigateTo or the tab at the bottom switches.
  • OnUpload-lifecycle function, which is used to listen for page uninstallation. It is called when wx. navigateTo and navigateBack are used.
  • OnPullDownRefresh-page related event processing function, used to listen to the user's drop-down action. however, enablePullDownRefresh must be enabled in the window option of config. After the data is refreshed, you can use wx. stopPullDownRefresh: Stop the pull-down refresh of the current page.

The following is the official code:

Page({     data: {         text: "This is page data."     },     onLoad: function(options) {     // Do some initialize when page load.     },     onReady: function() {       // Do something when page ready.     },     onShow: function() {     // Do something when page show.     },     onHide: function() {         // Do something when page hide.       },     onUnload: function() {         // Do something when page close.     },     onPullDownRefresh: function() {     // Do something when pull down       },     // Event handler.     viewTap: function() {       this.setData({ text: 'Set some data for updating view.'     })   }})

 

 

The above describes how to use the data attribute to set the page's initialization data, but what if we want to change the value in the data ?? Then we will introduce a setData () function officially provided to us. this function can send data from the logic layer to the data layer and change the value of this. data.

SetData ()Accept an object parameter and change the value of the key in this. data to value in the form of key and value. The following figure shows the official page lifecycle:


Page lifecycle Diagram

All the page routes in the Applet are managed by the Framework. You can call the API to call the routing trigger method and the page lifecycle function ..

Next we will briefly introduce the small program API.

The applet framework provides us with a wide range of native APIs for convenient calling, such as user information retrieval, local storage, and payment.

The following describes the API provision:

  • An API starting with wx. on is an API that listens to an event and accepts a CALLBACK function as a parameter. When an event is triggered, the CALLBACK function is called.

    • Unless otherwise specified, all other API interfaces accept an object as a parameter.
    • The OBJECT can specify success, fail, and complete to accept the interface call results.


      OBJECT Parameters


      For specific API calls, see the mini-program API documentation.

      Because I do not have an internal test number during the internal test of the applet, the specific API call code must be implemented according to the specific logic after the applet is opened. in addition, the API documentation has been very clear, and it is believed that the call will not be too difficult.

The above is the page registration and API function implementation of the applet page, but we know that this is not enough. Since the development of the Internet, we pay more attention to human-computer interaction, so that users can have a better experience to be considered a good program, then let's talk about how the applet renders the page.

A native rendering method is adopted in the applet. The page layout of the applet uses wxml. Then, the event system constructs the Page Structure Based on the basic components.

In wxml, there are data binding, conditional rendering, list rendering, templates, events, and references. The following describes these methods.

Data BindingAs we have mentioned above, when registering a Page on Page (), there will be a data attribute to define the initialization data, now, when binding data for page rendering, you need to call the data in data. The following is an official example.

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

 

 

From the code above, we can see that when the view layer accepts the code of the logic layer, We need to wrap the data key values with two braces to get the data value. Of course, the view layer can also perform operations (ternary, arithmetic), logical judgment, string operations, and can also be combined in braces (arrays, objects (Although they can be combined at will, if the variable names behind them are the same as the previous variable names, the latter will overwrite the previous)).

Conditional RenderingAs the name implies, conditional rendering is used to determine whether to render the code block. Conditional rendering is mainly used.Wx: ifAndBlock wx: ifThese two are the first to be well understood, and the second to implement conditional rendering in the block. Here we note that <block/> is not a component, it is just a packaging element, does not make any rendering in the page, only accept control attributes. Similar to our previous logic programming, since we have wx: if, we also have wx: elseif and wx. else, which can be combined to make conditional rendering more flexible.

Here, the official document mentions a comparison between wx: if and hidden. By using these two methods reasonably, you can make your program better. Let's talk about the differences between them:

Since wx: if may also contain data binding, when the conditional value of wx: if is switched, the framework has a partial rendering process, it will make sure that the condition is destroyed or re-rendered during the switchover. Meanwhile, wx: if is also inert. if the initial rendering condition is false, the frame will not do anything. Rendering will only start when the condition changes to true for the first time. In contrast, hidden is much simpler, and components are always rendered. It only controls display and hiding. In general, wx: if has higher switching consumption, while hidden has higher initial rendering consumption, which can be called as needed.

List rendering -- wx:

Next, let's talk about the usage of wx: for. By binding wx: for to an array, you can use the data in the array to repeatedly render the component,Note:The subscript variable name of the current item of the default array is index by default, and the variable name of the current item of the array is item. Of course, you can also redefine these two names as needed, using wx: for-item can specify the variable name of the current element of the array, wx: for-index can specify the variable name of the current underlying object of the array, wx: for can also be nested, in this case, you need to change the default framework name for the definition.

The following is the official example code:

<view wx:for="{{items}}"> {{index}}: {{item.message}}</view>Page({ data: { items: [{ message: 'foo', }, { message: 'bar' }] }})<view wx:for="{{array}}" wx:for-index="idx" wx:for-item="itemName">   {{idx}}: {{itemName.message}}</view>

 

 

Template

WXML provides a template. You can define code snippets in the template and call them in different places. the template of the applet can be named by name. When used, the is used to declare the template used, and then the data required by the template can be passed in, the following code is provided in the official document to show how to declare and call the template.

<!--  index: int  msg: string   time: string--><template name="msgItem">   <view>     <text> {{index}}: {{msg}} </text>     <text> Time: {{time}} </text>   </view></template>

 

 

The above Code shows that the template name is "msgItem ".

<template is="msgItem" data="{{...item}}"/>

 

 

The method used during the call is as shown in the preceding figure. Add the Template Name to the "is" attribute. There is a data attribute next to it and data is added to it. Let's take a look at the code in the "prepare" section.

Page({ data: { item: { index: 0, msg: 'this is a template', time: '2016-09-15' } }})

 

 

Some people may have some questions about the data binding content in the data attribute ,"{{... item }}" this call can expand the item object in the code above, so that data can call this template cyclically.

Of course, if the template function is just like this, its availability will be too bad. Of course, this will not happen, templates can also be rendered based on your own conditions. Let's take a look at the official code below.

<template name="odd">   <view> odd </view></template><template name="even">   <view> even </view></template><block wx:for="{{[1, 2, 3, 4, 5]}}">   <template is="{{item % 2 == 0 ? 'even' : 'odd'}}"/></block>

 

 

Based on the introduction of conditional rendering, we can see that after the array [1, 2, 3, 4, 5] is cyclically dropped, the item array attribute determines which template to call in the ternary operation.

Here, I would like to say that the template also has its own scope. Only data passed in can be used. Of course, the data passed in can be the data you created yourself, it can also be the initialization data you have written in the configuration.

Now that we have finished the template, some people may have to think about it. After I write the template, how should I call it? If they are on a page, it will certainly be okay, however, the availability is poor. What should I do if I want to place a template on a single page? It doesn't matter. The applet has long considered it. Let's talk about it next.Reference.

Reference

WXML provides two reference methods: import and include.

Next, let's talk about the import method. Let's look at the code. The template message that it calls on different pages is as follows:

<!-- item.wxml --><template name="item">   <text>{{text}}</text></template>

 

 

You can use the item template by referencing item. wxml in index. wxml:

<import src="item.wxml"/><template is="item" data="{{text: 'forbar'}}"/>

 

 

Here, we should note that the import reference also exists in the scope concept. It only defines the template defined in the import target file, rather than the template in the import target file. in short, import can only reference template, but cannot reference import.

As mentioned above, how is import referenced? Let's take a look at how include references.

The only difference between include reference and import is that its reference is equivalent to copying. It copies all the content in <template>, but does not contain <template>, I believe you can better understand the code.

<!-- index.wxml --><include src="header.wxml"/><view> body </view><include src="footer.wxml"/><!-- header.wxml --><view> header </view><!-- footer.wxml --><view> footer </view>

 

 

The view layer methods we mentioned above can already form a static page, but now we are in the 21st century. How can a program without human-computer interaction survive in this world? In today's most user experience, it is impossible for small programs to ignore this point. Next let's talk about the view layerEvent Method.

First, let's talk about what the incident is. I believe some people will be overwhelmed by what you are talking about. If you are so professional, I 'd better read the document. let's talk about what an event is.

An event is a form of communication from the page to the logic layer. For example, if you want machine feedback for your operations, the event will be used at this time. The event can feed user behavior back to the logic layer for processing.

There is another question, but how does one use it? Events can be bound to components. When an event is triggered, the corresponding event processing function of the logic layer is executed. To facilitate human-computer interaction, you can also carry additional information, such as id, data.

Someone may have said it after reading the section just now. Well, the event you just mentioned is almost explained, but why did you come up withComponentsWhich makes me so understand?

Now that we are talking about components, let's take a brief look at them. In the subsequent component sections, let's go into details about what an event is.

Why do we need components? Components are designed for developers to develop quickly.

What is a component? A component is the basic component unit of the view layer. In a applet, a component comes with some functional and style styles. A component usually includes the start tag and end tag. The attribute is used to modify the component, the content is within two tags.

<tagname property="value"> Content goes here ...</tagename>

 

 

Note that both components and attributes are in lowercase and connected.

A Brief Introduction to components, let's continue to talk about events.

Events are classified into bubble events and non-bubble events. A bubble event is a component event that is triggered and transmitted to the parent node, rather than a bubble event.

Currently, the applet only provides six bubble events (touchstart, touchmove, touchcancel, touchend, tap, and longtap), which are their respective trigger conditions.


Bubble Event Type

The rest are non-bubble events.

Next, let's talk about how to use the event?

Events are implemented through event binding. They are written in the form of key and value.KeyToBindAndCatchAnd keep up with the event type.ValueIs a string. You need to define a function with the same name in the corresponding page. Otherwise, an error will be reported when an event is triggered .(BindEvent binding does not prevent bubble events from bubbling up.CatchCan prevent the bubble event from bubbling up ).

After talking about how to bind events, let's talk about what the event processing function at the logic layer receives when an event is triggered? The event processing function receives an event object. What attributes does this event object have ?? The attributes include (type, timeStamp, target, currentTarget, touches, and detail). Their descriptions are as follows:


Event object attributes
  • Type is a common event type, such as tap.
  • TimeStamp is the number of milliseconds that occur when a page is opened to event triggering.
  • The source component of the target trigger event, which includes the id of the event source component, a set of Custom Attributes starting with data-, and its offset in the coordinate system.
  • CurrentTarget triggers the current event of the event, which includes the same content as the target.

For other attributes, follow the instructions above. Here we will talk about dataset in target and currentTarget. We know that data can be defined in components, the data will be transmitted to the SERVICE using the event writing method:Data-Start with event.tar. dataset converts a hyphen to camper elementType. I believe you will be more clear when using a piece of code.

<View data-alpha-beta = "1" data-alphaBeta = "2" bindtap = "bindViewTap"> DataSet Test </view> Page ({bindViewTap: function (event) {event.tar get. dataset. alphaBeta = 1 //-it will be converted into the camper method event.tar get. dataset. alphabeta = 2 // converts uppercase letters to lowercase letters }})

 

 

I don't know how everyone feels. If I just read a large part of the content I wrote at the beginning, I feel like I should be a mother-in-law, I will give you the code below. I believe that after reading the event, we will basically understand it.

// View layer event binding <view id = "tapTest" data-hi = "MINA" bindtap = "tapName"> Click me! </View> // Page ({tapName: function (event) {console. log (event) }}) // information output by the event processing function at the logic layer {"type": "tap", "timeStamp": 1252, "target ": {"id": "tapTest", "offsetLeft": 0, "offsetTop": 0, "dataset": {"hi": "MINA" }}, "currentTarget ": {"id": "tapTest", "offsetLeft": 0, "offsetTop": 0, "dataset": {"hi": "MINA" }}, "touches ": [{"pageX": 30, "pageY": 12, "clientX": 30, "clientY": 12, "screenX": 112, "screenY": 151}], "detail": {"x": 30, "y": 12 }}

 

Here we have finished the WXML page structure, and then let's briefly talk about WXSS.

A new dimension unit is introduced in WXSS.RpxIt specifies 1rpx = 0.5px = 1 physical Pixel

For WXSS style import, you can use the @ import statement to import the external style table. @ import is followed by the relative path of the external style table to be imported. Use; indicates that the statement ends. the remaining content is basically not the same as css. If you are interested, please refer to the official WXSS document.

The components and APIs of the Applet are easy to use.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.