To get started with mini programs, read this article

hzc
Release: 2020-06-16 10:42:09
forward
2664 people have browsed it

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!

Related labels:
source:juejin.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!