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

Cloud development data forms


May 22, 2021 Mini Program Cloud Development Study Guide


Table of contents


Most of the data used in the previous sections was written in js data, and in this section we'll show you how to get users to submit data. Whether it's calculators, user registrations, form collection, publishing articles, comments, and so on, these are all acquisitions of data submitted by users.

Set the navigation bar title

Dynamic settings navigation bar title is a very simple API, in the technical documentation can be learned, as long as the wx.set NavigationBarTitle() object assigned a title object, you can change the title of the small program page. Below we will use a variety of methods to call this API, both a review of the previous knowledge, but also let everyone understand how the API call method is different.

Technical documentation: wx.setNavigationBarTitle().

OnLoad calls the API

Combined with the previous knowledge, we can call the API in the lifecycle function of the page, create a new form page using the developer tool, and then add code to the form.js in the form-lyonLoad:

  1. onLoad: function (options) {
  2. wx.setNavigationBarTitle({
  3. title:"onLoad触发修改的标题"
  4. })
  5. },

Button calls the API

We can also call the API by clicking on the button component and triggering the event handler. Enter the following code in form.wxml

  1. <button type="primary" bindtap="buttonSetTitle">设置标题</button>

Then add the buttonSetTitle event handler in js:

  1. buttonSetTitle(e){
  2. console.log(e)
  3. wx.setNavigationBarTitle({
  4. title: "button触发修改的标题"
  5. })
  6. },

Then click on the setting title, button will trigger the event handler to re-assign the title, the title of the page will be changed from "onLoad trigger modified title" to "button trigger modified title", and click on the component will receive an event object, we print this event object e through the console.log printed out and found that there is no particularly useful information. These are the things we have learned before.

Use the form to modify the title

So how do we make the title content modified based on the data submitted by the user? T his involves the knowledge of the form. A complete data form collection for a small program usually consists of a form component, an input box or selector component (such as an input component), and a button component.

Use the developer tool to enter the following code in form.wxml:

  1. <form bindsubmit="setNaivgationBarTitle">
  2. <input type="text" placeholder="请输入页面标题并点击设置即可" name="navtitle"></input>
  3. <button type="primary" formType="submit">设置</button>
  4. </form>

Data forms involve many components (at least three), and there are many parameters and types of parameters, with a few very important points that you can understand in conjunction with the code above:

  • At the heart of the form is the form component form, the input box component input and button components are to be within the form, the form also collects data submitted by internal components;
  • Binding the event handler is no longer button, but form, form bindsubmit and button's formType "submit" is a pair, click button, will execute bindsubmit event handler;
  • input is an input box in which the user can add information, and name is the name of the input component, submitted with the form data.

Add the .js setNaivgationBarTitle to the form, and we print out the event object e:

  1. setNaivgationBarTitle(e) {
  2. console.log(e)
  3. const navtitle = e.detail.value.navtitle
  4. wx.setNavigationBarTitle({
  5. title:navtitle
  6. })
  7. },

After compilation, enter any text in the developer tool simulator, click the "Settings" button, and we find that the navigation bar title will show the values we entered. I n the console we look at the event object. The type property of the event object at this point is submit (formerly tab), and the value we fill in in the input box is stored in the name of the name of the value of the value property of the detail object, which is detail.value.navtitle.

Clicking on the button component will execute the form-bound event handler setNaivgationBarTitle, which prints the event object e, assigns the value entered in input to navtitle, and finally passes in to wx.setNavigationBarTitle(), assigned to itle. Note that there are two setNaivgationBarTitles, one for event handlers and one for APIs, the former which can be named arbitrarily, and the latter, which can't be changed by the official write-dead of small programs.

For data forms, using the console.log print event object gives us a very clear understanding of the data submitted by the form, while using assignments and setData can effectively render the data collected by the form to the page.

We can also write down the event handler above as follows, so that the variable title has the same name as setNavigationBarTitle's property title, so that title:title can be simply written into title.

  1. setNaivgationBarTitle(e) {
  2. const title = e.detail.value.navtitle
  3. wx.setNavigationBarTitle({
  4. title //等同于title:title
  5. })
  6. },

Text input box input

The input box input of the small program is mainly used to process the input of text and numbers, so let's combine the actual combat and technical documentation to understand the text input box input's type, name, placeholder and other properties.

Technical documentation: Input technical documentation

Using the developer tool to enter the following code in form.wxml, a form component can contain multiple selectors or text input box components, and when data is submitted, all the data filled in the form is submitted:

  1. <form bindsubmit="inputSubmit">
  2. <input type="text" name="username" placeholder="请输入你的用户名"></input>
  3. <input password type="text" name="password" maxlength="6" placeholder="请输入6位数密码" confirm-type="next" />
  4. <input type="idcard" name="idcard" placeholder="请输入你的身份证账号" />
  5. <input type="number" name="age" placeholder="请输入你的年龄" />
  6. <input type="digit" name="height" placeholder="请输入你身高多少米"/>
  7. <button form-type="submit">提交</button>
  8. </form>

Then add .js inputSubmit in the form element, mainly to print theform event object:

  1. inputSubmit:function(e){
  2. console.log('提交的数据信息:',e.detail.value)
  3. },

Input input box will be different because of the type of properties, the phone keyboard appearance will be relatively different, so you need to click on the preview, with WeChat scanning QR code experience on the phone (can also enable real debugging).

  • Input input box supports type values have text input text, digital input number, ID card input idcard, digit, when type is different, pay attention to the different appearance of the phone keyboard;
  • placeholder: placeholder: placeholder when the input box is empty (i.e. default); maxlength: maximum input length; password and disabled are both boolean values, using the same boolean properties as in previous video components.

In the developer tool's console we can see the value object in the printed event object, the property name is the name of the name of the input, and the value is the data entered for us. If there is no name.

Small tasks: configure the input input box with conferm-type, enter send, search, next, go, done, and then click preview, scan the QR code experience with WeChat, pay attention to the different input, the phone keyboard display.

A combination of form components

A complete data collection form, in addition to submitting the data inside the input text box, you can also submit the switch selector button switch switch, slide selector button slider, radio button radio, multi-button checkbox and other components of the data.

Technical documentation: switch switch selection, Slider slide selection, Radio radio, checkbox multiple selection, form form

Use developer tools to add the following code to form.wxml, which are scenarios that we often use on a daily basis, such as apps, pages, and so on:

  1. <form bindsubmit="formSubmit" bindrest="formReset">
  2. <view>开关选择器按钮</view>
  3. <switch name="switch"/>
  4. <view>滑动选择器按钮slider</view>
  5. <slider name="process" show-value ></slider>
  6. <view>文本输入框</view>
  7. <input name="textinput" placeholder="要输入的文本" />
  8. <view>单选按钮radio</view>
  9. <radio-group name="sex">
  10. <label><radio value="male"/></label>
  11. <label><radio value="female"/></label>
  12. </radio-group>
  13. <view>多选按钮checkbox</view>
  14. <checkbox-group name="gamecheck">
  15. <label><checkbox value="game1"/>王者荣耀</label>
  16. <label><checkbox value="game2"/>欢乐斗地主</label>
  17. <label><checkbox value="game3"/>连连看</label>
  18. <label><checkbox value="game4"/>刺激战场</label>
  19. <label><checkbox value="game5"/>穿越火线</label>
  20. <label><checkbox value="game6"/>天天酷跑</label>
  21. </checkbox-group>
  22. <button form-type="submit">提交</button>
  23. <button form-type="reset">重置</button>
  24. </form>

Then add .js formSubmit and formReset event handler in the form file

  1. formSubmit: function (e) {
  2. console.log('表单携带的数据为:', e.detail.value)
  3. },
  4. formReset: function () {
  5. console.log('表单重置了')
  6. }

Once compiled, select the selector and text input components in the developer tool's simulator and add some values, then click the submit button. I n console console, we can see that the value object of the event object e records the data we submitted. That is, the data submitted by the form component is stored in the value under the detail property of the event object e.

  • switch attribute: record the value selected by the switch, which is a boolean value, ture for on, false for off;
  • sex property: records the value of a phone button named sex, which records only the value of the item selected;
  • process properties: Record the value of the name of the sliding selector named process,
  • Show-value is the boolean value, showing the current value of the value, the data type is number;
  • textinput property: record the value of the input text input box named textinput;
  • Gamecheck properties: Record the value of a multi-select component named gamecheck with an array of arrays.

Clicking the reset button resets the form without additional processing from the formReset event handler.

We found that the button properties above, sometimes with form-type, sometimes with formType (note the case of both), both of which can be written. We can also delete the reset event handler formReset, as well as the form component's bindreset , "formReset", just set the form-type of button to reset, <button form-type="reset"&重置</button& and reset
You can achieve the effect of resetting, binding the event handler bindreset

As long as we know where the data stored in the form form can be combined with the previous knowledge to take the data out, different data types are treated differently, so it is important to know how to use JavaScript to manipulate different data types.

In the technical documentation, the words "When you click on the button component of form-type as submit in the form form, the value value in the form component is submitted and name needs to be added to the form component as key". We also found that Lider sliding selection, Radio radio radio, checkbox multiple selection, etc., have their own value, that is, these components do not need name when used alone in the event object detail to get the value of the value, and when combined use, you must add name to get the value, you can cancel the name to see how the results.

The extended operator of the array

Here we first introduce the concept of extension operators, which are written in a very simple way, that is, three points ... We'll use the case to let everyone know what it does first, and we'll use it a lot later.

Gamecheck above records the multi-option value we ticked, which is an array of Aray. We can print out the option value in the formSubmit event handler and add the following statement to theformSubmit function above:

  1. formSubmit: function (e) {
  2. const gamecheck=e.detail.value.gamecheck
  3. console.log('直接打印的gamecheck',gamecheck)
  4. console.log('拓展运算符打印的gamecheck',...gamecheck)
  5. },

Then we fill out the form submission data again, and you can see from the console that you can print gamecheck directly, it's an array Ofray, the parenthesis , you can see that the expansion also has index values, and the extension operator to print gamecheck, is to traverse the values in the array. T his is the extension operator... the role that we can only understand first.

Add a phone contact

Although we submitted the data, when the small program recompiles, all the data is reset, i.e. the submitted data is not saved. T here are three ways for a small program to store data, one is stored on a local phone, the other is stored in a cache, and the third is stored in a database. Let's show you how to store your data on your phone.

Add your phone contacts: wx.addPhoneContact().

Use the developer tool to add the following code in form.wxml, note that the name of the name of the input corresponds to and is consistent with the name of the property in wx.addPhoneContact(), just a few properties are listed below, and more properties can be added according to the technical documentation

  1. <form bindsubmit="submitContact">
  2. <view>姓氏</view>
  3. <input name="lastName" />
  4. <view>名字</view>
  5. <input name="firstName" />
  6. <view>手机号</view>
  7. <input name="mobilePhoneNumbe" />
  8. <view>微信号</view>
  9. <input name="weChatNumber" />
  10. <button type="primary" form-type="submit">创建联系人</button>
  11. <button type="default" form-type="reset">重置</button>
  12. </form>

Then enter .js code in the form file (note that adding a phone contact's API is amazingly effective on your phone)

  1. submitContact:function(e) {
  2. const formData = e.detail.value
  3. wx.addPhoneContact({
  4. ...formData,
  5. success() {
  6. wx.showToast({
  7. title: '联系人创建成功'
  8. })
  9. },
  10. fail() {
  11. wx.showToast({
  12. title: '联系人创建失败'
  13. })
  14. }
  15. })
  16. },

After compilation, click on the developer toolbar preview, WeChat scan the QR code, and then fill the above input data and click to create a contact, you can store the data in the phone.

The multi-write callback functions success(), fail(), and the addition of a message prompt box wx.showToast() can greatly enhance the user experience. I t is important to write more .log in programming, and to write more callback functions that allow us to diagnose the operation of the program. However, for the convenience of teaching, we will write fewer callback functions later.

The extended operator of the object

Earlier we covered the expansion operators of arrays, the extension operators of objects ... T here is also a type that takes out all traversable properties in an object and copies them into the new object. To get a better look, we can make print comparisons:

  1. submitContact:function(e) {
  2. const formData = e.detail.value
  3. console.log('打印formData对象',formData)
  4. console.log('扩展运算符打印', { ...formData })
  5. },

Although the printed results don't seem to make any difference, formData is a variable, and we assign the object to it, and the result of printing it is an object, and . . . FormData is an object in itself, equivalent to copying properties and values from a formData object into a new object.

Small task: Put wx.addPhoneContact() in... F ormData to formData, see what the results are? P ut... W hat's the result of formData replacing it with lastName? Why does writing lastName report errors, and writing formData doesn't report mistakes?

Input binds the event handler

In form forms, although there are input components in the form, the binding event handler is the form component, which provides only values for values, and the input text input component itself can bind the event handler. From the technical documentation we know that input can bind event handler properties are: bindinput, trigger when keyboard input, bindfocus, trigger when the input box is focused, bindblur, trigger when the input box is out of focus, etc.

Bindinput responsive data rendering

Use the developer tool to enter the following code in form.wxml, where the event handler bindKeyInput (the function name can be named after itself) is used input's bindinput binding event handler.

  1. <view>你输入的是:{{inputValue}}</view>
  2. <input bindinput="bindKeyInput" placeholder="输入的内容会同步到view中"/>

In Page's data we add the initial value of inputValue,

  1. data: {
  2. inputValue: '你还没输入内容呢'
  3. },

After compiling, we can see that the values in the data are rendered to the page, which is what we learned earlier.

Let's add the following code to the input-bound event handler bindKeyInput in the form .js (declare a variable name with the same variable name as the property in data, and assign the value, setData can be short-formed, as seen in this section).

  1. bindKeyInput: function (e) {
  2. const inputValue = e.detail.value
  3. console.log('响应式渲染',e.detail)
  4. this.setData({
  5. inputValue
  6. })
  7. },

After compilation, we fill in the input content, note that at this time we write the content will be rendered to the page in real time, whether it is adding content or deleting content, you can make a synchronous response. And in console Console, we can also see a real-time print result for every one character entered/deleted, where cursor is the cursor when the cursor is the cursor position.

Note: Recall our previous data rendering, there is direct initialization written in Page data, there is the use of page lifecycle and button way to trigger event handlers with setData to change the data rendering, there is also form data collection, these data rendering is not responsive, that is, without refreshing the page, the data will be rendered in real time according to your modifications.

Clipboard

The added phone contacts earlier in this section store the collected data in the contacts of the local phone, while the clipboard stores the data in the cutboard of the local phone.

Technical documentation: Set the cutboard content wx.setClipboardData(), get the cutboard content wx.getClipboardData().

Use the developer tool to enter the following code at form.wxml:

  1. <input type="text" name="copytext" value="{{initvalue}}" bindinput="valueChanged"></input>
  2. <input type="text" value="{{pasted}}"></input>
  3. <button type="primary" bindtap="copyText">复制</button>
  4. <button bindtap="pasteText">粘贴</button>

Then in Page's data we add the initial values of initvalue, pasted,

  1. data: {
  2. initvalue: '填写内容复制',
  3. pasted: '这里会粘贴复制的内容',
  4. },

Then .js event handler valueChanged, button component-bound two event handler copyText, pasteText:

  1. valueChanged(e) {
  2. this.setData({
  3. initvalue: e.detail.value
  4. })
  5. },
  6. copyText() {
  7. wx.setClipboardData({
  8. data: this.data.initvalue,
  9. })
  10. },
  11. pasteText() {
  12. const self = this
  13. wx.getClipboardData({
  14. success(res) {
  15. self.setData({
  16. pasted: res.data
  17. })
  18. }
  19. })
  20. },

Enter content in input, the content will respond to rendering to the page, click the copy button, copyText event handler will call the API to assign data to the data cutboard data (note that the data here is not the data page data, is the properties of the wx.setClipboardData API), and click the paste button, the event handler pasteText will call the interface, Assign the data inside the callback function res to the pasted in the page data, and the page renders the lasted in the data in real time without refreshing it.

Small tasks: Above we use input's value property, change the value to placeholder, compare the difference between the two. A s we said earlier, the cutboard is to store the data in the cutting board of the local phone, use the preview to open the small program in the phone to copy the content, and then to WeChat chat interface, use paste to see the effect. Or copy a piece of content on your phone and open the little program to tap paste to see what works.

Slider responds by setting the color

The slider slide selector can also bind event handlers, such as events triggered after bindchange completes a drag, and events triggered during a bindchanging drag.

Technical documentation: Sliding selector slider

Let's first review the data carried by the data in the event object and the data carried by the form component: first, the data of the component data-property is stored in the property name of the dataset under the current Target in the event object, that is, the value of data-color is stored in e.currentTarget.dataset.color, and the data of the form component is stored in the event object's detail, that is, e.detail.value.

Use the developer tool to enter the following code in form.wxml, which will involve both data carried by data-and-data carried by form components:

  1. <view style="background-color:rgb({{R}},{{G}},{{B}});width:300rpx;height:300rpx"></view>
  2. <slider data-color="R" value='{{R}}' max="255" bindchanging='colorChanging' show-value>红色</slider>
  3. <slider data-color="G" value='{{G}}' max="255" bindchanging='colorChanging' show-value>绿色</slider>
  4. <slider data-color="B" value='{{B}}' max="255" bindchanging='colorChanging' show-value>蓝色</slider>

Then in Page's data we add the initial values of R, G, B (children's shoes that don't know the RGB color value can be searched, they take values between 0 and 255), where the initial values of R, G, B are both the initial values of the three colors of background-color, but also the initial value of the sliding selector, we set it to green (vi color of the small program technical document)

  1. data: {
  2. R:7,
  3. G:193,
  4. B:96,
  5. },

Then add .js event handler, colorChanging, that is bound by the slider component to the form:

  1. colorChanging(e) {
  2. console.log(e)
  3. let color = e.currentTarget.dataset.color
  4. let value = e.detail.value;
  5. this.setData({
  6. [color]: value
  7. })
  8. },

After compilation, as we slide the slider, the background color of the view component changes. W hen sliding a slider, colorChanging is constantly triggered by a sliding drag (similar to the state of ing in English, real-time monitoring), and multiple values are printed in the console Console, e.detail.value is the value of the drag, while e.currentTarget.dataset.color always has only three results R, G, B, and the value is assigned to R, The three values are G and B.

Picker component

Picker scroll selectors look very complex, but the small program has helped us encapsulate them, and we only need a few simple lines of code to make a very complex and diverse scroll selector.

Technical documentation: Scroll selector picker

Using the developer tool to enter the following code in form.wxm, you can bounce a date scroll selector from the bottom with just a few lines of code below. And the text inside can be filled in at will, similar to the words in the button, navigator components, click to perform the corresponding events.

  1. <picker mode="date" value="{{pickerdate}}" start="2017-09-01" end="2022-09-01" bindchange="bindDateChange">
  2. 选择的日期为:{{pickerdate}}
  3. </picker>
  • mode properties: scroll selectors have several modes, different modes can pop up different types of scroll selectors, here is the date selection, other modes are generally similar;
  • Start and end properties: This is a date selector-specific property, for the start and end of the valid date, we can scroll under, beyond this range can not scroll;

Then in Page's data we add the initial value of the pickerdate

  1. data: {
  2. pickerdate:"2019-8-31",
  3. },

Then add .js event handler bindDateChange to the form code, and let's print and see the event object of the packer component:

  1. bindDateChange: function (e) {
  2. console.log('picker组件的value', e.detail.value)
  3. },

After compilation, when we bounce the scroll selector, the date selector points by default to the initial value of August 31, 2019, and when we swipe to select a date to determine, we can see the selected date in the console console. This date is a string.

Small task: So how do we take the selected dates, such as 2019-10-21, from here (i.e. 2019, 10, 21)? T his involves the operation of strings, remember the operation of strings? You can look at the JavaScript Standard Library of MDN technical documentation, there are many ways to take out specific numbers, do you know what to do?

In this section, we talk about how data can be stored on a local phone, and in a later section, we talk about other ways of storing data, such as caching, databases, and so on. Do you feel that programming is logical processing, calling APIs, and playing with data...