Summarize some small program development skills
This article shares some WeChat mini program development tips for everyone, hoping to help the majority of developers.
1. Use of global variables
Each mini program needs to call the App method in app.js to register the mini program example and bind the life cycle callback function. Error monitoring and page monitoring functions do not exist, etc.
For detailed parameter meanings and usage, please refer to the App reference document.
The entire mini program has only one App instance, which is shared by all pages. Developers can obtain a globally unique App example through the getApp method, obtain data on the App, or call functions registered by developers on the App.
When we make small programs, we often need a large number of requests, and the domain names requested are also the same. We can store the domain name in a global variable, which will facilitate the modification of the domain name requested later. . (Frequently used ones such as user_id, unionid, user_info can be placed in global variables)
//app.js App({ globalData: { user_id: null, unionid:null, url:"https://xxx.com/index.php/Home/Mobile/", //请求的域名 user_info:null } })
Remember to quote app.js when using it on the page, the mini program has provided methods
//index.js //获取应用实例 const app = getApp() //获取app //let url = app.globalData.url; //使用方法,可先定义或者直接使用app.globalData.url wx.request({ url: app.globalData.url + 'checkfirst', //就可以直接在这里调用 method:'POST', header:{"Content-Type":"application/x-www-form/"} data:{}, success:(res)=>{}
2. The use of arrow functions
When we call an interface request and change the page data through the data returned by the request, we often use a temporary pointer to save this pointer.
But if you use ES6 arrow functions, you can avoid it
Use temporary pointers
onLoad: function (options) { let that = this //保存临时指针 wx.request({ url: url + 'GetCouponlist', method: 'POST', header: { 'Content-Type': 'application/x-www-form-urlencoded' }, data: { }, success(res) { that.setData({ //使用临时指针 coupon_length:res.data.data.length }) } })
Use ES6 arrow functions ( ) => {}
success:(res) => { this.setData({ //此时this仍然指向onLoad coupon_length:res.data.data.length }) }
3. Encapsulation of HTTP request method
In small programs, http requests are very frequent, but typing wx.request every time is very annoying, and the code is also redundant. There is more, so we need to encapsulate it
First we need to create a new js in the utils folder, I named it request.js, and encapsulate the post and get requests in it. Remember to declare it at the end
//封装请求 const app = getApp() let host = app.globalData.url /** * POST 请求 * model:{ * url:接口 * postData:参数 {} * doSuccess:成功的回调 * doFail:失败回调 * } */ function postRequest(model) { wx.request({ url: host + model.url, header: { "Content-Type": "application/x-www-form-urlencoded" }, method: "POST", data: model.data, success: (res) => { model.success(res.data) }, fail: (res) => { model.fail(res.data) } }) } /** * GET 请求 * model:{ * url:接口 * getData:参数 {} * doSuccess:成功的回调 * doFail:失败回调 * } */ function getRequest(model) { wx.request({ url: host + model.url, data: model.data, success: (res) => { model.success(res.data) }, fail: (res) => { model.fail(res.data) } }) } /** * module.exports用来导出代码 * js中通过 let call = require("../util/request.js") 加载 */ module.exports = { postRequest: postRequest, getRequest: getRequest }
This step is very important, remember to add it!
module.exports = { postRequest: postRequest, getRequest: getRequest }
When used, it is called at the top of the corresponding page, outside the Page
let call = require("../../utils/request.js")
When used, ↓
get
//获取广告图 call.getRequest({ url:'GetAd', success:(res)=>{ //箭头函数没有指针问题 this.setData({ urlItem: res.data }) } })
post
call.postRequest({ url: 'addorder', data: { shop_id: that.data.shop_id, user_id: app.globalData.user_id, coupon_sn: that.data.coupon_sn, carType: that.data.car_type, appointtime: that.data.toTime }, success:(res)=>{ console.log(res) wx.navigateTo({ url: '../selectPay/selectPay?order_sn=' + res.data.order_sn + '&fee=' + res.data.real_pay + "&order_id=" + res.data.order_id, }) } })
4. In the search input, how to click the search button to search and modify the button style
Normally we will add a search button to the search box and click to search, but the mini program It does not operate on the dom, so it cannot directly obtain the value in the input, so it needs to be searched through another method.
(1) Through the bindconfirm attribute in the input component (confirm-type="search", you can change the completion button of the soft keyboard to "search")
<input class='search_input' type='text' confirm-type='search' bindconfirm='toSearch' ></input> //js部分 toSearch(e){ console.log(e.detail.value) //e.detail.value 为input框输入的值 }
(2) Use the form submission to complete the submission of the click button (input needs to add the name attribute)
Search button
Use button instead of form submission ( form-type="submit"), please note that you cannot use view, you must use button
You need to modify the default style of the button yourself (the border of the button must be modified in button::after)
//wxml部分 <form bindsubmit="formSubmit" bindreset="formReset"> <input class='search_input' type='text' confirm-type='search' name="search" bindconfirm='toSearch' > <button class='search_btn' form-type='submit'>搜索</button></input> </form>
//js部分 formSubmit(e){ console.log(e.detail.value.search) //为输入框的值,input记得添加name属性 }
Related recommendations: Mini Program Development Tutorial
The above is the detailed content of Summarize some small program development skills. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

Win11 tricks revealed: How to bypass Microsoft account login Recently, Microsoft launched a new operating system Windows11, which has attracted widespread attention. Compared with previous versions, Windows 11 has made many new adjustments in terms of interface design and functional improvements, but it has also caused some controversy. The most eye-catching point is that it forces users to log in to the system with a Microsoft account. For some users, they may be more accustomed to logging in with a local account and are unwilling to bind their personal information to a Microsoft account.

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

Forms are an integral part of writing a website or application. Laravel, as a popular PHP framework, provides rich and powerful form classes, making form processing easier and more efficient. This article will introduce some tips on using Laravel form classes to help you improve development efficiency. The following explains in detail through specific code examples. Creating a form To create a form in Laravel, you first need to write the corresponding HTML form in the view. When working with forms, you can use Laravel

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.
