Home WeChat Applet Mini Program Development To get started with mini programs, read this article

To get started with mini programs, read this article

Jun 16, 2020 am 10:42 AM
WeChat applet

Explanation

The article is about the pitfall experience and solutions in actual combat. At the same time, it is a project review of my own. I share it with everyone here. I hope it can help everyone. If you find the article useful to you, please give it a like, thank you! Forgive me for being a headliner:)

Login authorization

Authorization (basic information, mobile phone number) must use the button component native to the mini program, and then specify open- The user information can be obtained through callback after type. The code is as follows:

index.wxml
<view wx:if="{{!getUserInfo}}">
       <view>你还未登录,请先授权登录</view>
            <button open-type="getUserInfo" bindgetuserinfo="bindGetUserInfo">
                授权登录
            </button>
        </view>
        <view wx:if="{{getUserInfo && !getPhone}}">
            <view>你还未绑定手机号,请先去绑定</view>
            <button open-type="getPhoneNumber" bindgetphonenumber="getPhoneNumber">
                立即绑定
            </button>
</view>
index.js
page({
    // ... 
    data: {
        hasUserInfo: false,
        canIUse: wx.canIUse(&#39;button.open-type.getUserInfo&#39;),
        userInfo: {},
        getUserInfo: false,
        getPhone: false,
        hasAuth: false
    },
    onLoad: async function () {
        var that = this;
        // 查看是否授权
        wx.getSetting({
            success: function (res) {
                if (res.authSetting[&#39;scope.userInfo&#39;]) {
                    wx.login({
                        success: loginRes => {
                            // 获取到用户的 code 之后:loginRes.code
                            wx.getUserInfo({
                                success: async function (res) {
                                    // 这里处理业务逻辑
                                }
                            })
                        }
                    })
                } else {
                    // 用户没有授权
                }
            }
        });
    },
    bindGetUserInfo: function (e) {
        // 需要什么信息都从e中拿到 以下部分业务逻辑
        if (e.detail.userInfo) {
            //用户按了允许授权按钮
            var that = this;
            // 获取到用户的信息
            wx.login({
                success: async res => {
                    const aUserModel = new UserModel();
                    const params = {
                        code: res.code,
                        encryptedData: e.detail.encryptedData,
                        iv: e.detail.iv
                    }
                    const { data } = await aUserModel.login({ ...params })
                    if(data.roles){
                        // do ...
                    }
                    if (data.mobile) {
                        // do ...
                    }
                }
            });
            //授权成功后,通过改变 isHide 的值,让实现页面显示出来,把授权页面隐藏起来
            that.setData({
                isHide: false
            });
        } else {
            //用户按了拒绝按钮
            wx.showModal({
                title: &#39;警告&#39;,
                content: &#39;拒绝授权,您将无法使用小程序&#39;,
                showCancel: false
            });
        }
    },
    getPhoneNumber: async function (e) {
        if (e.detail.encryptedData) {
            //用户按了允许授权按钮
            const aUserModel = new UserModel();
            const params = {
                userId: userInfo.id,
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv
            }
            // do ...
        } else {
            //用户按了拒绝按钮
            wx.showModal({
                title: &#39;警告&#39;,
                content: &#39;拒绝授权,您将无法使用小程序&#39;,
                showCancel: false
            })
        }
    },
    // ...
})
Copy after login

Routing

You can go to the official website to learn the various methods of route jump. Here are the pitfalls encountered. NavigateTo route jump can only be up to 10 levels, so when using it You need to consider whether historical records are definitely needed. Why do you say that? Scenario: A list page (as shown below), the user's profile can be modified. If you use navigateTo to jump (/page/archivesEdit?id=1923XXXX), use navigateTo (/page/archivesList) to modify and save, so that you can edit and jump back and forth. Clicks will no longer be allowed to jump after 10 times.

To get started with mini programs, read this article

Solution: Think about it, can I use 2 redirectTo? redirectTo closes the current history record and jumps to the next page. As a result, I jumped to the modification page and clicked on WeChat's own return function, which directly skipped the list page and jumped to the homepage. At this time, the test girl has to submit a bug ticket again. . .
Perfect posture: Just use navigateTo and navigateBack. When I edit and save, I use navigateBack to return. In this way, the routing stack of the mini program will be between layers 2-3. Of course, sometimes the interface needs to be called again on the list page. At this time, routing jump provides several important hook functions onShow and onHide. We can call the list interface during onShow.

These two hook functions are enough for us to make a simple jump. In more complex scenarios, we can return to the previous page for operation by saving access parameters such as Storage. It does not feel elegant, but there is no Good solution.

Storage


Scenario: There are two ways to obtain storage. When you directly get an id with wx.getStorageSync('xxx'), go to The request interface may have been sent before the request was obtained, resulting in a bug.

Because wx.getStorageSync('xxx') is asynchronous, we can use async/await to use it conveniently

onLoad: async function (options) {
        const editListParams = await wx.getStorageSync(&#39;editListParams&#39;)
        this.findReportDetails(editListParams)
}
Copy after login

webView


webview is not used on a certain page. At that time, I thought it was something like an iframe embedded into the page. The correct usage attitude is to create a new page and then jump to this page to use it. For example, jump to the official account article associated with the mini program:

other.wxml
<navigator url="/pages/webView/webView"  hover-class="none">跳转到webView</navigator>
webView.wxml
<web-view src="https://mp.weixin.qq.com/s/xxxx"></web-view>
Copy after login

request


WeChat’s own request under the network, although you can use it if you can , if not encapsulated, it will cause code redundancy. You can refer to the following encapsulation

ajax.js

import { baseURL } from &#39;../config/interfaceURL&#39; // baseUrl

class AJAX {
    AJAX ({ url, methods = &#39;GET&#39;, data = {} }) {
        return new Promise((resolve, reject) => {
            this.request(url, resolve, reject, methods, data)
        })
    }
    request (url, resolve, reject, methods, data) {
        wx.request({
            url: baseURL + url,
            method: methods,
            data: data,
            header: {
                &#39;content-type&#39;: &#39;application/json&#39;
            },
            success: res => {
                const code = res.statusCode.toString()
                if (code.startsWith(&#39;2&#39;)) {
                    resolve(res)
                } else {
                    reject()
                    const errorMessage = res.data.message
                    AJAX.showError(errorMessage)
                }
            },
            fail: err => {
                reject()
                AJAX.showError("网络异常,请稍后重试!")
            }
        })
    }
    static showError (errorMessage) {
        wx.showToast({
            title: errorMessage,
            icon: &#39;error&#39;,
            duration: 2000
        })
    }
    static serializeLink (obj) { // 序列化get请求
        let temp = &#39;?&#39;
        for (let index in obj) {
            if(obj.hasOwnProperty(index)){
                temp += (index + &#39;=&#39; + obj[index] + &#39;&&#39;)
            }
        }
        return temp.substr(0, temp.length - 1)
    }
}
export default AJAX

// model层调用
UserModel.js
import AJAX from &#39;../utils/AJAX&#39;

export class UserModel extends AJAX {
    // 小程序授权登陆
    login (params) {
        return this.AJAX({
            url: `/service/api/users/applet/login`,
            data: params,
            methods: &#39;POST&#39;
        })
    }
}
// control调用
index.js
async onLoad (options){
    const aUserModel = new UserModel()
    const params = {
        code: loginRes.code,
        encryptedData: res.encryptedData,
        iv: res.iv
    }
    const { data } = await aUserModel.login({ ...params })
    // 其他
}
Copy after login

npm ecology and third-party UI framework


There is no package.json file in the WeChat applet project that is initialized directly. So it is useless to use npm install xxx. So we have to execute npm init ourselves in the root directory of the folder. Only then can npm be built through the WeChat developer tools. A directory will be generated if the build is successful. It is recommended to use the vant mini program version of Youzan. The community is more active and there will not be many pitfalls in using it.

Two-way binding


For developers who are accustomed to using vue, this v-model syntax sugar is missing. Dealing with two-way binding of forms can be a pain in the ass. So it is still necessary to talk about the two-way binding in the mini program.

file:index.js

Page({
    data: {
       list: []
    },
    onLoad: function (options) {
      // do ...
    },
    onInput (e) {
        let value = e.detail.value
        let temp = e.target.dataset.name.split(&#39;,&#39;)
        let tempKey = temp[1]
        let tempIndex = temp[0]
        let tempSubIndex = temp[2]
        let targetKey = `list[${tempIndex}].children[${tempSubIndex}].${tempKey}`
        this.setData({
            [targetKey]: value
        })
    }
})

file:index.wxml
<block  wx:for="{{item.children}}"  wx:for-item="subItem"  wx:key="{{index}}">
    <view class="td" style="height: {{ 100 / item.children.length}}%;">
      <input placeholder-style="color:#ccccccc;"  type="text" placeholder="未填写" value="{{subItem.testResult}}" data-name="{{idx}},testResult,{{index}}"  bindinput="onInput"/>
    </view>
</block>
Copy after login

Downloading images and downloading image authorization


The scenario here is to download a fixed static resource image. The network image needs to be configured with the download domain name before it can take effect. The method As follows:

 savePhoto () {
        const _this = this;
        wx.getImageInfo({
            src: &#39;/static/images/home/Qr.png&#39;,
            success: function (res) {
                wx.saveImageToPhotosAlbum({
                    filePath: res.path,
                    success (result) {
                        _this.setData({ show: false });
                        wx.showToast({
                            title: &#39;保存成功&#39;,
                            icon: &#39;success&#39;,
                            duration: 2000
                        })
                    },
                    fail (err) {
                        if (err.errMsg === "saveImageToPhotosAlbum:fail auth deny") {
                            wx.openSetting({
                                success (settingdata) {
                                    if (settingdata.authSetting[&#39;scope.writePhotosAlbum&#39;]) {
                                        _this.savePhoto()
                                    } else {
                                        wx.showToast({
                                            title: &#39;获取权限失败,无法保存图片&#39;,
                                            icon: &#39;success&#39;,
                                            duration: 2000
                                        })
                                    }
                                }
                            })
                        }
                    }
                })
            }
        })
    }
Copy after login

Saving pictures also requires authorization, just look at the code and you're done.

Others


textarea will have padding value on ios. This is a trap for me. I use either all textarea or all input to fill in the form. There are also quite a few other style issues, a bit like IE. ! ! Use flex float more to solve some differences~

Conclusion


Every point in the article is a problem encountered when developing small programs. My ability is limited. , everyone is welcome to ask questions, exchange and learn in the comment area, and you can also follow the Haoxiangjia official account to get more high-quality articles.

Recommended tutorial: "WeChat Mini Program"

The above is the detailed content of To get started with mini programs, read this article. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

WeChat applet implements image upload function WeChat applet implements image upload function Nov 21, 2023 am 09:08 AM

WeChat applet implements picture upload function With the development of mobile Internet, WeChat applet has become an indispensable part of people's lives. WeChat mini programs not only provide a wealth of application scenarios, but also support developer-defined functions, including image upload functions. This article will introduce how to implement the image upload function in the WeChat applet and provide specific code examples. 1. Preparatory work Before starting to write code, we need to download and install the WeChat developer tools and register as a WeChat developer. At the same time, you also need to understand WeChat

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

Implement image rotation effect in WeChat applet Implement image rotation effect in WeChat applet Nov 21, 2023 am 08:26 AM

To implement the picture rotation effect in WeChat Mini Program, specific code examples are required. WeChat Mini Program is a lightweight application that provides users with rich functions and a good user experience. In mini programs, developers can use various components and APIs to achieve various effects. Among them, the picture rotation effect is a common animation effect that can add interest and visual effects to the mini program. To achieve image rotation effects in WeChat mini programs, you need to use the animation API provided by the mini program. The following is a specific code example that shows how to

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

Implement the sliding delete function in WeChat mini program Implement the sliding delete function in WeChat mini program Nov 21, 2023 pm 06:22 PM

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

See all articles