Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Cloud Development page rendering


May 22, 2021 Mini Program Cloud Development Study Guide


Table of contents


In the Data Binding section, we've learned how to render data from inside data to a page, and in this section we'll show you how to modify the data inside data in data by clicking on the event handler bound by the component, and how to print the data obtained by the event handler to the page.

Render variable values to the page

Remember the Date object, Math object, string String object, and constant that we used to print in the console? I n the first section we assign these objects to a variable, and then through the console we can print these values to console.log(), so can these values be rendered to the page of the small program? The answer is yes.

Render variable values to the page

Use the developer tool to create a new page, such as data, and then enter the following code in front of the data.js's Page function, which is not written in the Page function, and on the first line of the data.js:

  1. let lesson = "云开发技术训练营";
  2. let enname = "CloudBase Camp";
  3. let x = 3, y = 4, z = 5.001, a = -3, b = -4, c = -5;
  4. let now = new Date();

Note that these are the statements of the JavaScript function above, so they use a sign; S eparation, don't confuse this with the previous comma separation. I f the statement is newer, followed by a sign; You can also write without having to.

Then add the following data to the data (note that there are no double quotes, single double quotes are strings)

  1. data: {
  2. charat: lesson.charAt(4),
  3. concat: enname.concat(lesson),
  4. uppercase:enname.toUpperCase(),
  5. abs:Math.abs(b),
  6. pow: Math.pow(x, y),
  7. sign:Math.sign(a),
  8. now:now,
  9. fullyear:now.getFullYear(),
  10. date:now.getDate(),
  11. day: now.getDay(),
  12. hours: now.getHours(),
  13. minutes: now.getMinutes(),
  14. seconds: now.getSeconds(),
  15. time: now.getTime()
  16. },

Enter the following code in data.wxml:

  1. <view>"云开发技术训练营"第5个字符 {{charat}}</view>
  2. <view>两个字符串连接后的结果:{{concat}}</view>
  3. <view>CloudBase Camp字母大写:{{uppercase}}</view>
  4. <view>b的绝对值:{{abs}}</view>
  5. <view>x的y次幂:{{pow}}</view>
  6. <view>返回a是正还是负:{{sign}}</view>
  7. <view>now对象:{{now}}</view>
  8. <view>{{fullyear}}年</view>
  9. <view>{{date}}日</view>
  10. <view>星期{{day}}</view>
  11. <view>{{hours}}时</view>
  12. <view>{{minutes}}分</view>
  13. <view>{{seconds}}秒</view>
  14. <view>1970年1月1日至今的毫秒数:{{time}}</view>

Because data is an object Object, we can assign variable values to properties in data in a colon: in the data binding section, the data can be rendered directly to the page of the small program.

ToString() method

We found that the result of the rendering was an object, object Object, and did not display string text, and this time we needed to use the object's toString() method to get the object's string. Change the assignment of data now to the following:

  1. now:now.toString(),

Technical documentation: ToString() method

The data binding of the response

Data data in the logical layer js file, whether it's the underlying string, array, object, etc., or the value assigned through variables, can be rendered to the page. Not only that, but as long as the data in the logical layer data is modified, the view layer is updated accordingly, which we call the data binding of the response, which is done through Page's setData() approach.

Use the developer tool to enter in data.wxml:

  1. <view style="background-color:{{bgcolor}};width:400rpx;height:300rpx;"></view>
  2. <button bindtap="redTap">让背景变红</button>
  3. <button bindtap="yellowTap">让背景变黄</button>

Then add .js data to the data display

  1. bgcolor:"#000000",

Then add two button-bound event handler, redTap and yeellowTap, to the js:

  1. redTap:function(){
  2. this.setData({
  3. bgcolor: "#cd584a"
  4. })
  5. },
  6. yellowTap:function(){
  7. this.setData({
  8. bgcolor: "#f8ce5f"
  9. })
  10. },

Click button, the background color of the original view component changed from black to other colors, because clicking on the component triggered the event handler, called Page's setData() method modified the value of the corresponding property in the data (repeated assignment is modified), bgcolor from the original "#000000" into other data.

Small tasks: Through past learning we learned that whether it is the style of components, pictures, linked paths, arrays, objects in the data, they can be separated data written into the data inside, which means that we can change the data inside the data through click events can achieve a lot of unexpected effects, please use your imagination to do some interesting cases out.

The Boolean operation of the response

As we've seen earlier, some components have data types for private properties such as video, whether the Swiper carncast component plays automatically, whether the video component displays a play button, and so on, which we can all use setDatatrue to false to true for control purposes.

In terms of interaction, the response Boolean operation can be used for switching between a single property true and afalse, such as display and hide, expand and collapse, focus and lose focus, select and uncheck.

Let's look at a case where the developer tool is used to enter the following code in data.wxml:

  1. <video id="daxueVideo" src="http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400" rel="external nofollow" autoplay loop muted="{{muted}}" initial-time="100" controls event-model="bubble">
  2. </video>
  3. <button bindtap="changeMuted">静音和取消静音</button>

Then add a .js data in data

  1. muted: true,

Then add the changeMuted event handler

  1. changeMuted: function (e) {
  2. this.setData({
  3. muted: !this.data.muted
  4. })
  5. },

Clicking the button in the developer tool simulator, we found that mute and un mute are both buttons. The exclamation point here! is logical non-meaning and can be understood as not.

This.setData and this.data both use the keyword this. This and Chinese in the "this" have a similar fingering effect, in the method, this refers to the method belongs to the object, such as here is the Page object, this.data refers to the Page function object data object.

The array operation of the response

Combining the knowledge of click events and array operations, let's look at the following example to learn how to add and delete data from an array by clicking a button.

Use the developer tool to enter the following code in data.wxml, noting that there is only one view layer here, which means that we will then assign all the data to the text in data.

  1. <view>{{text}}</view>
  2. <button bindtap="addLine">新增一行</button>
  3. <button bindtap="removeLine">删掉最后一行</button>

Then declare the .js before the data is called Page(), which declares extraLine as an empty array, and we add and delete data to that array later.

  1. let initData = '只有一行原始数据'
  2. let extraLine = [];

And then add a data in Page's data,

  1. text: initData,

Let's start by looking at the logic of data rendering when there is no event handler, first we assign the initData variable value to text, and then the result of the rendering is only the data in initData, so the page shows "only one row of raw data", and extraLine has nothing to do with text.

Let's add add addline and removeLine event handler to Page:

  1. addLine: function (e) {
  2. extraLine.push('新增的内容')
  3. this.setData({
  4. text: initData + '\n' + extraLine.join('\n')
  5. })
  6. },
  7. removeLine: function (e) {
  8. if (extraLine.length > 0) {
  9. extraLine.pop()
  10. this.setData({
  11. text: initData + '\n' + extraLine.join('\n')
  12. })
  13. }
  14. },

First, review the previous knowledge of array operations, push adds data to the end of the array, and pop deletes the data on the last row of the array, join is the connector before the array data.

Click the button to add a new line, trigger binding event handler addLine, will first execute the extraLine array to add a new data "new content", but then extraLine and text is not related, then insetData () function will be initData and extraLine stitching (note that extraLine was originally an array, B ut when the line method is called, it returns a stitched string of the values of the array). Clicking the button to delete the last row deletes the data on the last row in the extraLine array.

Small task: The new content is too single, we can add a random number after extraLine.push('新增的内容') extraLine.push('新增的内容'+Math.random()) and then take a look at the effect of the new data, about Math.random() you can go to MDN to check it out. You can also change the stitched connector \n another character.

Functions and calling functions

The function can write the code once and reuse it over and over again. JavaScript's functions themselves are objects, so they can be assigned to variables or passed as arguments to other functions.

The definition and structure of the function

We can use the function keyword to define a function, in parentheses () for the function's arguments, parameters can be many, using commas, separated;

  1. function 函数名(参数 1, 参数 2, 参数 3) {
  2. 代码块内要执行的语句
  3. }

Functions without arguments

For example, let's use developer tools to .js the Page() function of the data system:

  1. function greet() {
  2. console.log("你好,欢迎来到云开发训练营");
  3. };
  4. greet(); //调用greet()函数

After saving, we can see the string printed by the function in the console. D efining a function does not automatically execute it. D efining a function simply gives it a name and clarifies what to do when it is called. T he function is called to actually perform these actions with a given argument. The greet() function has no arguments, and when the function is called, write the function name and parenthesis directly.

A function with only one argument

A simple square function square() is defined below, square is the function name, number is the parameter of the function (the name can be customized), using the return statement to determine the return value of the function. Let's continue with .js the following code before the Data-based Page() function:

  1. function square(number) {
  2. return number * number;
  3. };
  4. square(5);

square (5), that is, assign 5 to the variable number, and then execute the number number, that is, 5 5, and then return the value of the return.

The number here is called the ginseng, and 5 is called the real ginseng. You can combine the case to get a general understanding of the meaning of the form and the real ginseng.

  • A parameter is an argument used to define a function in order to receive the actual arguments that come in when the function is called.

  • Arguments are arguments that are passed to a function at the time of the call

JavaScript allows any argument to be passed in without affecting the call, so there can be more, but not less, arguments passed in than defined. This means that the number of real ginseng can be more than the shape ginseng but not less than the form ginseng.

The method of the object

In small programs we often assign an anonymous function to an object's property, which we can call the object's method.

Anonymous function

Function declaration fusion is syntaxally a statement, but functions can also be created by function expressions that do not have a function name (anonymous).

Using the developer tool, .js the following code before using the data to enter the Page() function:

  1. let square = function(number) {
  2. return number * number
  3. };
  4. console.log(square(4))//使用console.log()输出变量square

After execution, you can see the output result of 16 in the console. The function above has no function name, which is equivalent to assigning the return value of the function to the variable square.

The arrow function

Why is it called arrow function, because it defines a function with an arrow, let's look at two examples and enter the following code before the Data.js Page() function:

  1. const multiply = (x, y) => {
  2. return x * y;
  3. }
  4. const sum= (x, y) => x + y;//连{}和return语句都可以省掉
  5. console.log(multiply(20, 4));
  6. console.log(sum(20, 4));

In the console we can see the result of the arrow function printing. A rrow functions are equivalent to anonymous functions, they don't have function names, and they simplify function definitions. T he arrow function can contain only one expression, or even a . . . a nd return can be omitted. You can first only need to understand this writing on it, later encounter not to be more confused, see more also try to write more.

The method that called the object

You can use point notation to call the method of an object, which is no different from the properties that access the object. The method of calling an object and calling a function are much the same.

The method that calls the object we've been exposed to a lot of cases before, as we've already said earlier, wx is a global object for a small program, and in the first section we printed a lot of APIs that called the method in the wx object.

How JavaScript functions are written

In the Click Events section, the event click handler we created is written as follows:

  1. scrollToPosition() {
  2. },

In this section we create an event click function written as:

  1. yellowTap:function(){
  2. },

Both of these writings can be executed, we can modify these two writings to each other to try

CurrentTarget event object

In the previous list rendering, we know that clicking on a movie in the movie list, to make a page jump to show the details of the movie, we need to create a page for the movie, then if you want to show the details of thousands of movies, one by one to create movie details page is obviously not appropriate, after all, all the movie details page is the same structure, there is no way all movie details are shared a page, but according to the click of the link, render the corresponding data? The answer is yes, to solve this problem, we first need to understand the click information of the link component.

When a component is clicked to trigger an event, the handler of the logical layer binding the event receives an event object through which some information about when the event is triggered, such as timestamps, details, and some collection of property values of the current component, especially the id of the event source component.

CurrentTarget is a property of an event object that represents the current component of the event binding. Use the developer tool to enter the following code in data.wxml

  1. <view class="weui-navbar">
  2. <block wx:for="{{tabs}}" wx:key="index">
  3. <view id="{{index}}" class="weui-navbar__item {{activeIndex == index ? 'weui-bar__item_on' : ''}}" bindtap="tabClick">
  4. <view class="weui-navbar__title">{{item}}</view>
  5. </view>
  6. </block>
  7. </view>
  8. <view class="weui-tab__panel">
  9. <view hidden="{{activeIndex != 0}}">帝都</view>
  10. <view hidden="{{activeIndex != 1}}">魔都</view>
  11. <view hidden="{{activeIndex != 2}}">妖都</view>
  12. <view hidden="{{activeIndex != 3}}">渔村</view>
  13. </view>

Then add the .js data to the data in the data:

  1. tabs: ["北京", "上海", "广州", "深圳"],
  2. activeIndex:0,

Then add the event handler tabClick.

  1. tabClick: function (e) {
  2. console.log(e)
  3. this.setData({
  4. activeIndex: e.currentTarget.id
  5. });
  6. },

After compilation, preview in the emulator. When we click on the tab above, the tabClick event handler is triggered, at which point the event handler receives an event object e, we can look at the contents of the e object printed by the console, and the interpretation of the specific properties of the e object can be seen in the technical documentation.

Technical documentation: Event object

CurrentTarget is a property of the event object, and we can use the point notation to get the Id of the clicked component and assign it to activeIndex, which means activation, that is, which tab we click and which tab activates.

  • When the click id is 0, that is, the first tab, the value of activeIndex is modified to 0 by the event handler;

  • ActiveIndex , index the same tab, that is, the activated tab will have weui-bar__item_on class, which will also appear in green

  • The !-is is not equal to the operator, activeIndex!=0 obviously does not set the condition for false, that is, the component Hidden is false, that is, for display, while activeIndex! ?

When we don't know the information contained in strings, Math objects, Date objects, array objects, function objects, event objects, print them out. T he printed results are basically strings, lists, objects, and we've seen how to manipulate them before. By printing logs, we can debug code and strengthen our understanding of logic.