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

Cloud development lifecycle


May 22, 2021 Mini Program Cloud Development Study Guide


Table of contents


From the previous study, we learned that functions can manipulate (add and delete) data (including strings, arrays, objects, Boolean and all other data types), components have attribute data, and also have the ability to be programmed, so that the importance of carrying data (id, class, style and even click events are component-carried data, can be used for programming). This section provides insight into how components carry data, what event object data does, and how data is rendered across pages.

Links carry data

The special character of the URL link

In daily life, we can often see some links are particularly long, such as Baidu, JD.com, Taobao and other search for a keyword link, the following is the use of Baidu search cloud development links:

  1. https://www.baidu.com/s?ie=utf-8&f=8&rsv_bp=1&rsv_idx=1&tn=baidu&wd=云开发&rsv_pq=81ee270400007011&rsv_t=ed834wm24xdJRGRsfv7bxPKX%2FXGlLt6fqh%2BiB9x5g0EUQjyxdCDbTXHbSFE&rqlang=cn&rsv_enter=1&rsv_dl=tb&rsv_sug3=20&rsv_sug1=19&rsv_sug7=100&rsv_sug2=0&inputT=5035&rsv_sug4=6227

and the video links you used in the video components earlier:

  1. http://wxsnsdy.tc.qq.com/105/20210/snsdyvideodownload?filekey=30280201010421301f0201690402534804102ca905ce620b1241b726bc41dcff44e00204012882540400&bizid=1023&hy=SH&fileparam=302c020101042530230204136ffd93020457e3c4ff02024ef202031e8d7f02030f42400204045a320a0201000400

These links usually include the following special characters, and all have the same meaning, through which the links are stuffed into a lot of data information, which? , , ,

  • / Separate directories and subdirectors

  • ? Separates the actual URL from the parameters

  • The separator between the parameters specified in the URL

  • The value of the parameter specified in the URL

  • A location identifier for the same page, similar to a bookmark for a page;

Get the url-linked data

Use the developer tool, create a new lifecyle page, and create a new secondary page detail on the home page (i.e. create a new page/home/detail/detail in the pages configuration item, and pay attention to setting lifecycle to the home page) and enter the following code in lifecyle.wxml, where url also passes? , , ,

  1. <navigator id="detailshow" url="./../home/detail/detail?id=lesson&uid=tcb&key=tap&ENV=weapp&frompage=lifecycle" class="item-link">点击链接看控制台</navigator>

Clicking on the link shows that the page can still jump to the detail page, and the data added to the url does not change the path of the page, which is usually controlled by/.

So what's the point of the data that the link carries? You find no, originally clicked on the link in lifecycle, but jumped to detail, if the link carries the data is always there, as long as we can get the linked data in the detail, then we have achieved the cross-page data?

Gets the life cycle function of the url parameter onload

Onload is a lifecycle function of page Page that is triggered when the page loads. A page is called only once, and you can get the arguments in the path to the open current page in the arguments of the onLoad function.

Using the developer tool, .js the onload function in the .log function and print out the parameters of the onload function:

  1. onLoad: function (options) {
  2. console.log(options)
  3. },

Clicking on the link to the lifecycle.wxml page again will jump to detail, the life cycle callback function onload will be triggered when the page loads, the parameters in the function will be printed, we can look at the console printing information.

  1. {id: "lesson", uid: "tcb", key: "tap", ENV: "weapp", frompage: "lifecycle"}

I'm sure you'll be familiar with this data type, it's an object Object, and we can get specific properties in the object through point notation, such as options.id to show the id of the component we click on in lifecycle.

The data spans the page

Go back to the movie list page of the previous list rendering section (you can copy and paste the previous wxml and wxsss and data code from the movie list into lifecycle), add some information to the Navigator component, and find the following code:

  1. <navigator url="" class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active">

Change it to the following, i.e. add id, name, img, desc, and more to the link

  1. <navigator url="./../home/detail/detail?id={{index}}&name={{movies.name}}&img={{movies.img}}&desc={{movies.desc}}" class="weui-media-box weui-media-box_appmsg" hover-class="weui-cell_active">

After compilation, click on one of the movies on the lifecycle page, we find that all links will still jump to detail, but the console output information is different, click on which movie, will output in the console which movie information, the data not only achieves cross-page, but also realizes the point which shows which distinction.

Cross-page data rendering

Of course, we can also continue to render the data using setData to the detail page, so that we can only render picture information, enter in detail.wxml:

  1. <image mode="widthFix" src="{{detail.img}}" sytle="height:auto"></image>

Add a detail .js data in the data of the detail object, and the detail object has three properties that are used to receive setData data, so it can be an empty value:

  1. detail:{
  2. name:"",
  3. img:"",
  4. desc:""
  5. },

Then assign the value of options to detail in the onload lifecycle function

  1. onLoad: function (options) {
  2. console.log(options)
  3. this.setData({
  4. detail: options,
  5. }
  6. )
  7. },

So, which movie we click on in lifecycle, and which movie's poster is shown on the detai page.

However, the use of link url delivery parameters are byte-limited and can only be used across pages, but can be used to pass such as page link source, can track the user from what device, what app, by which way and from which friend's invitation link; Across multiple pages and passing more parameters, data, and more, you can use the public data storage app.globalData (described in this section), data caching (described later), database (described in the cloud development section), and the new inter-page communication interface getOpenerEventChannel (not much here)

Components carry data data data

Components have public and private properties, which are data that event handler can modify to give the component a rich representation. N ot only that, you can attach some custom data to the component node. In events, these custom node data can be obtained for logical processing of events, making components fairly complex and powerful programming objects.

Use JavaScript instead of the Navigator component

Use the developer tool to enter the following code in lifecycle.wxml,

  1. <image id="imageclick" src="https://img13.360buyimg.com/n7/jfs/t1/842/9/3723/77573/5b997bedE4f438e5b/ccd1077b985c7150.jpg" rel="external nofollow" rel="external nofollow" mode="widthFix" style="width:200rpx" bindtap="clickImage"></image>

Then we added the following code to the lifecycle .js, and in the previous section we said that when a click component triggers an event, the handler of the logical layer binding the event receives an event object, which we still print out:

  1. clickImage:function(event){
  2. console.log('我是button',event)
  3. wx.navigateTo({
  4. url: "/pages/home/detail/detail?id=imageclick&uid=tcb&key=tap&ENV=weapp&frompage=lifecycle"
  5. })
  6. },

When we click on the picture on the lifecycle page, clickImage receives an event object that prints out two properties, target and current Target, which point to the element bound by the event, and target always points to the element at the time of the event. Since the elements bound by this case event and the elements at the time of the event are imageclicks, they all have the same values, they all contain the id of the current component, and dataset, so what is this dataset?

It is worth emphasizing that many children's shoes think that only click on the Nasagator component, button component can be linked jump, which is the wrong way of thinking, through bindtap, the component is given a certain degree of programming ability, although there is no url attribute, the use of wx.navigateTo can also have this ability.

Custom property dataset

Let's add a parent component to the image above, where the data-sku, data-spu, and data-pid values, as well as the pictures, use JD.com iPhone data. These custom data begins with data- and multiple words are connected by a hyphen.

  1. <view id="viewclick" style="background-color: red;padding:20px;" data-sku="100000177760" data-spu="100000177756" data-pid="100000177756" data-toggle="Apple iPhone XR" data-jd-color="Red" data-productBrand="Apple" bindtap="clickView">
  2. <image id="imageclick" src="https://img13.360buyimg.com/n7/jfs/t1/842/9/3723/77573/5b997bedE4f438e5b/ccd1077b985c7150.jpg" rel="external nofollow" rel="external nofollow" mode="widthFix" style="width:200rpx" bindtap="clickImage">点击button</image>
  3. </view>

Then add the event .js clickView in the lifecycle page,

  1. clickView: function (event) {
  2. console.log('我是view',event)
  3. wx.navigateTo({
  4. url:"/pages/home/detail/detail?id=viewclick&uid=tcb&key=tap&ENV=weapp&frompage=lifecycle"
  5. })
  6. },

When we click on the red space (non-image area), only clickView is triggered, and target is the same value as current Target. And when we click on the picture, two event handleres are triggered.

We clicked on the image image component, but triggered the event handler bound to the image component and the parent (up level) component view of the image, which we call event bubbling.

Note that the values of the clickView event objects are different at this point. In the case of clicking on the image, only in the clickView event object'scurrent Target can you see that dataset gets custom data for the view component.

At the same time from the print of the detail page (note that the link between the two events has a different value of id), click on the picture, jump to the image bound to the event-specified page, the page id is imageclick.

Let's look at the values of dataset and find jdColor and productbrand, because dataset converts hyphen writing into hump writing, and capital characters automatically turn into lowercase characters. D ata-jd-color became jdColor, while data-productBrand became productbrand. That is, we click on the component, and from the dataset of the event object, we can get the custom data of the component through the event.currentTarget.dataset.

Click the component to display additional data for the current component

Event objects allow us not only to know exactly what component was clicked, but also to get custom data for the current component. For example, in the case above, we can easily get the pid of JD.com's product and jump to the details page of the product (https://item.jd.com/ JD.com's pid.html), which we can add in the clickView event handler:

  1. let jdpid=event.currentTarget.dataset.pid
  2. let pidurl = "https://item.jd.com/" + jdpid + ".html"
  3. console.log(url)

This way the details page linking the item is printed out (the small program does not support the chain jump of the navigateTo). If we want to get other relevant data about the current component, it's very convenient to use event objects, such as clicking on a small diagram to display a large diagram, toggle popping up other content, and so on.

The small program also supports adding wxss styles to the data-property, for example, we can add styles to data-pid, view(data-pid) (margin:30px; Isn't the data-property powerful to exist like a selector or to program it?

The lifecycle of small programs and pages

App() function registration program, Page() function registration program in a page, they all accept the object Object type parameters, including some lifecycle functions and event handlers. A pp() must be .js in the app, must be called, and can only be called once. Developers can add any function or data variable to the Object parameter, which can be accessed with this.

Small program constructor: Object object

Page constructor: Object object

Small tasks: Why can't we just assign variables with equal signs in apps () and Page()? D o you understand? Note that function statements and object properties and methods are written differently.

Print logs to understand the lifecycle

For the lifecycle of small programs and pages, we can print logs to understand the specific execution order and situation of lifecycle functions, using developer tools to add some print logs to onLaunch, onShow, and onHide in the app.js

  1. onLaunch(opts) {
  2. console.log('onLaunch监听小程序初始化。',opts)
  3. },
  4. onShow(opts) {
  5. console.log('onShow监听小程序启动或切前台',opts)
  6. },
  7. onHide() {
  8. console.log('onHide监听小程序切后台')
  9. },

It must have been noted that some parameters are written options, some are written is opts;

and add .js js in lifecylce

  1. onLoad: function(options) {
  2. console.log("onLoad监听页面加载",options)
  3. },
  4. onReady: function() {
  5. console.log("onReady监听页面初次渲染完成")
  6. },
  7. onShow: function() {
  8. console.log("onShow监听页面显示")
  9. },
  10. onHide: function() {
  11. console.log("onHide监听页面隐藏")
  12. },
  13. onUnload: function() {
  14. console.log("onUnload监听页面卸载")
  15. },

By performing various actions in the simulator, such as compiling, clicking the forward button, clicking the close button next to the small program forward button (not closed), page switching, etc. to understand the order of execution of life cycle functions (such as page life cycle), the cutting forebe and cut background, page loading, rendering, display, hiding, uninstalling have a certain understanding.

As we have learned before, by clicking on an event you can trigger an event handler, that is, you need the user to click on a component to trigger it, and here the lifecycle function of the page can also trigger an event handler, which does not require the user to click on the component, just need the user to open a small program, open a page, cut the small program into the background, etc. to trigger the function inside.

The small program opens the scene value

There App a onLaunch 1001 in the onShow printed objects, which is the scene value. S cene values are used to describe how a user enters a small program. There are many ways for users to enter your small program, such as scanning QR code, some long-pressing image recognition QR code, some through WeChat group into the small program, some friends single chat into the small program, some through the public number into the small program and so on, these are scene values, and specific scene values, can see technical documents, scene values for products, operations are very important.

Technical documentation: A list of scene values

onLaunch and onShow

onLaunch is the initialization of the listening small program, triggered when the initialization is complete, the global trigger only once, so here we can use to execute some very core data, such as functions to get user login information, if there are too many functions onLaunch, will affect the startup speed of the small program.

onShow is triggered when a small program starts, or when it enters the forewith display from the background, that is, it triggers many times, and here it is not a good place to put functions that get user login information. The difference between the two should be noted.

User login and information acquisition

Small program user login and access to user information is relatively complex, in order to enable everyone to more intuitively combine our previous knowledge to step by step to explore what is going on, it is recommended that we re-build a small program project that does not use cloud services.

Learn about wx.login, wx.getSetting

Use the developer tool to .js the app's code as follows (you can delete or comment out all of the previous ones and copy and paste the following code). Learn about a function, an API, and the real-world aspects start with printing logs, while the theoretical aspects start with the technical documentation.

  1. App({
  2. onLaunch: function () {
  3. wx.login({
  4. success(res){
  5. console.log('wx.login得到的数据',res)
  6. }
  7. })
  8. wx.getSetting({
  9. success(res){
  10. console.log('wx.getSetting得到的数据',res)
  11. }
  12. })
  13. },
  14. globalData: {
  15. userInfo: null
  16. }
  17. })

The template program uses the arrow function writing method, we can combine the previous introduction about the arrow function, the template small program code and the above writing contrast to learn.

From the console, you can see that wx.login gets err Msg and code, which are the user's login credentials. T he wx.getSetting, on the other hand, gets the current permission settings for errMsg and the user, including whether to allow access to user information, whether to allow access to the user's location, whether to allow permissions such as mobile phone albums. We can understand this in depth based on the printed results combined with technical documentation.

Technical documentation: Get the user login credentials wx.login, get the user's current permission settings wx.getSetting

If it's not enough to get the applet and your own server account through, it's not enough to just get the user login credentials, you need to send this code and your applet appid and appSecret back to your development server, and then call the ath.code2session interface on your own server to get the user's openid and session_key. S ince openid is the unique identity of the current user, it can be used to determine whether the user has registered on his or her own server, and if so, to generate a custom login status based on openid and return it to the applet, the process is complex. And because cloud development and WeChat login forensics seamless integration, these content will not be involved, so here is not much to introduce.

Get user information wx.getUserInfo

We want to get user information, first of all, we need to determine whether the user is allowed, you can see from the authSetting object whether the scope.userInfo property is true, if it is true, then we can call the wx.getUserInfo() interface to get user information.

Use the developer tool to add content to the wx.getSetting() function above, and the final code is as follows:

  1. wx.getSetting({
  2. success(res){
  3. console.log('wx.getSetting得到的数据',res)
  4. if (res.authSetting["scope.userInfo"]){
  5. wx.getUserInfo({
  6. success(res){
  7. console.log("wx.getUserInfo得到的数据",res)
  8. }
  9. })
  10. }
  11. }
  12. })

Since scope.userInfo is a property name and cannot be obtained using point notation res.authSetting.scope.userInfo to get its value (which would be mistaken for the usrInfo property value of the scope property under the autoSetting property), another way of representing the object's properties, called parenthesis notation, is used to surround the property name with a parenthesis. Property names need to be surrounded by single or double quotes.

In the console console we can see that the userInfo object contains the currently logged-in user's nickname, profile picture, gender, and more.

globalData

But this data is in the .js, and the data we have been exposed to before is different in the js file of the page. And this user information data is all pages are common, put in the app .js public should be, but how can we call this data?

GlobalData objects are often used to hold data that will be used by the entire gadget, for example, we can assign user information to any custom property of globalData. The template gadget has declared a userInfo property, and we can customize other property names, such as (we'll use it later)

  1. tcbData:{
  2. title:"云开发训练营",
  3. year:2019,
  4. company:"腾讯Tencent"
  5. },

The userInfo object obtained is assigned to the userInfo property of the global Data object in the success callback function of the wx.getUserInfo above.

  1. wx.getUserInfo({
  2. success(res){
  3. console.log("wx.getUserInfo得到的数据",res)
  4. this.globalData.userInfo = res.userInfo
  5. }
  6. })

But it prompts Cannot read property 'globalData' of undefined; E rrors, but template programs are also written in this way why not errors? This is because the arrow function's this is different from the non-arrow function's this pointing.

that and this

This's pointing situation is very complex, although which object calls the function, the function inside the tis points to which object, it is very simple to say, but there are too many scenes, we do not have to force understanding in development, rote met, the this printed out can be. We can print out the this of the callback function success,

  1. success(res){
  2. console.log('this是啥',this)
  3. }

The result is that the is undefined, there is no definition, and we expect the Page() function object is not consistent, give it the this.globalData assignment of course will be wrong.

There are two solutions, one is that the template program uses the arrow function, the arrow function inherits the external object this, we can code wx.getSetting() in the success callback function is written to the arrow function (there are two, only change one line?). Try it), and then we can print the this again to see what's going on.

In the console we can see that the result of this after changing to an arrow function is a pe object that contains the lifecycle functions and properties of the Page() object.

The second method is to use the tat to write a line of code in front of the wx.getSetting() function:

  1. let that=this
  2. wx.getSetting({............}) //为了便于你找位置

Then change the success callback function of wx.getUserInfo to the following:

  1. wx.getUserInfo({
  2. success: res =>{
  3. console.log('that是啥',that)
  4. console.log("wx.getUserInfo得到的数据",res)
  5. that.globalData.userInfo = res.userInfo
  6. }
  7. })

Because of the complexity of the situation, this's pointing often changes, but when the tis's point is still a Page() object, we assign the this to theth, so that there is no underfined because the this is pointing to a change.

getApp()

So how do we call globalData in the js of the page, and we need to use the getApp() function at this time.

Technical documentation: getApp().

Use the developer tool to create a new user page, and then .js the page() function in the user's application:

  1. let app = getApp()
  2. console.log('user页面打印的app', app)
  3. console.log('user页面打印的globalData', app.globalData.userInfo)
  4. console.log('user页面打印的tcbData',app.tcbData.eventInfo)

That way we can get .js the globalData and custom properties in the app's website.

There will also be a problem here, even though we have obtained globalData, we can also see the user's information in the print log of globalData.userInfo, but when we want to get the value inside, we will still report errors, because wx.getUserInfo is asynchronously obtained information, the asynchronous involved here, we will go into more detail later.

Get user information through button

When we use the wx.getUserInfo method to obtain user information, the console will report an error: Get the wx.getUserInfo interface will no longer appear authorized spring 获取 wx.getUserInfo 接口后续将不再出现授权弹窗,请注意升级。 That is, the small program official has not recommended developers with wx.getUserInfo to obtain user information, but suggested that through button way to obtain, the user experience is better, that is, the user only click the button, user information will be obtained.

Enter the following code in user.wxml using the developer tool, which is a button component that has two prerequisites for obtaining user information, one is open-type,""getUserInfo," which must be this value, and the other is that the property that bindgetuserinfo (similar to bindtap, but the property name must be bindtusgeerinfo), As for the name of the event handler can be customized)

  1. <button open-type="getUserInfo" bindgetuserinfo="getUserInfomation"> 点击获取用户信息 </button>

The getUserInfomation here is consistent with the event handler for the previous click event, the click component triggers getUserInfomation, and still receives the event object, which we print out and add the following code to the user.js:

  1. getUserInfomation: function (event) {
  2. console.log('getUserInfomation打印的事件对象',event)
  3. },

When we click on the button "click to get user information", in the console can see getUserInfomation printed event object, event object has a detail property, there is userInfo data, this specific how to call, detailed in conjunction with the previous knowledge should be understood.

First, a .js object is initialized in the data of the user database to receive the data:

  1. data: {
  2. userInfo:{}
  3. },

Then the userInfo obtained by the event handler getUserInfo assigns it by thethis.setData, which is the function of getUserInfomation

  1. getUserInfomation: function (event) {
  2. console.log('getUserInfomation打印的事件对象',event)
  3. this.setData({
  4. userInfo: event.detail.userInfo,
  5. })
  6. },

At this point the userInfo in data has user information, we can add the following code in user.wxml to render the data.

  1. <view>{{userInfo.nickName}}</view>
  2. <view>{{userInfo.country}}</view>
  3. <image mode="widthFix" style="width:64px;height:64px" src="{{userInfo.avatarUrl}}"></image>

When we click the button again to get user information, the data is rendered.

Write user information into the app .js

This way you can only get user information on the user page, the restrictions are very large, so what should we do? We want to write the user information obtained into the .js the public information of the page, you can later cross the page just click the button once on the user page.

In getUserInfomation, the user information obtained is passed to globalData's userInfo property:

  1. getUserInfomation: function (event) {
  2. console.log('getUserInfomation打印的事件对象',event)
  3. app.globalData.userInfo = event.detail.userInfo
  4. this.setData({
  5. userInfo: event.detail.userInfo,
  6. })
  7. },

Regarding user login and information acquisition, here we just combed through some of the more core knowledge points, and some people can refer to the template in the small program code, here is a relatively complete set of cases. More practical user sign-in, which will be covered later in the Cloud Development section.

Another way to get user information is to show it through the components . . . open-data . . . because it's simpler, there's not much to introduce here.