Project background

In 19, I was in charge of a ToB real estate industry project in the previous company. In 18, I finished the development of PC terminal, and then I had to simultaneously develop small programs. Another small program project is the previous company’s PC portal official website, also need to develop small program synchronously.

This article is to sort out and record all kinds of difficulties, API problems, bugs, and tutorial sorting (updated from time to time) 😁 in the process of using wechat small program to develop products

The body of the

Mustache data binding for WXML pages does not allow you to use global JS methods, such as time/date formatting, price formatting, etc., as defined in utils.js.

Can only use. WXS file, this is the document: developers.weixin.qq.com/miniprogram… Also. WXS files can only use ES4 syntax, not ES6 syntax, and some symbols, such as the mailbox re I used in my VUE project, will give an error.

const emailReg = /[\w!#$%&'*+/=?^_`{|}~-]+(? :.[\w!#$%&'*+/=?^_`{|}~-]+)*@(? :[\w](? :[\w-]*[\w])? .). +[\w](? :[\w-]*[\w])? /;
Copy the code

< WXS SRC =”… < WXS SRC =”… < WXS SRC =”… /.. / utils/util. WXS “module =” util “/ >.

However, there are limitations in using.wxs as a global method, such as moment.js and accounting.js, which are widely used third-party plug-ins. WXS files cannot reference JS files, but only.wxs files.

So this is a bit of a nuisance, so I have to go ahead and use utils.js to define the global method inside and import it in the app.js entry as follows:

/** * global public method *@type {function}* /
const utils = require('./utils/utils.js');

App({
    // Global public methods
    utils: utils,
})
Copy the code

Next, if you need to use unit conversions in a list page or detail page, such as US dollars and RMB prices and square feet and square meters conversions that require a global approach to the data. It’s easy to use: declare variables in data in test.js, and then use global methods below to process data. Example:

/* test.js */

// Get the global application instance object
const app = getApp();

Page({
    /** * initial data for the page */
    data: {
        price: null,},/** * lifecycle function -- listens for page loading */
    onLoad: function (options) {
        // You can only use the util global method to process data with variables declared by data
        
        // Check whether the data field returned by the server interface is null, such as res.data.price = 123
        this.setData({ price: app.utils.isNull0(res.data.price) }); }})Copy the code
/* test.wxml */

<view>{{ price }}</view>

<! <view>123</view> </view> </view> </view>
Copy the code

These are the small program page sub-route page how to use utils global method of the whole content, this point is I start small program these days encountered more disgusting 🤢, compared to the development of webApp project with VUE, small program this point is really anti-human, very inconvenient 😱.

I use “appellate” and “iView-appellate” UI libraries.

Usage:

Vant – weapp: youzan. Making. IO/vant weapp /…

IView-weapp:weapp.iviewui.com/docs/guide/…

Download the dist file to the components directory of the applet, then define the usingComponents field in app.json, which component to use, according to the guide of its official documentation. Insert the component into the usingComponents. Note that the relative path must be set properly, otherwise an error will be reported. For example, the small program project I am currently developing temporarily uses these components. After the development, the components that are not used in the dist directory can be deleted.

"usingComponents": {
    "van-row": ".. /components/vant-weapp/dist/row/index"."van-col": ".. /components/vant-weapp/dist/col/index"."van-toast": ".. /components/vant-weapp/dist/toast/index"."van-notify": ".. /components/vant-weapp/dist/notify/index"."van-tab": ".. /components/vant-weapp/dist/tab/index"."van-tabs": ".. /components/vant-weapp/dist/tabs/index"."van-search": ".. /components/vant-weapp/dist/search/index"."i-spin": ".. /components/iView-weapp/dist/spin/index"."i-button": ".. /components/iView-weapp/dist/button/index"."i-drawer": ".. /components/iView-weapp/dist/drawer/index"
}
Copy the code

This method is not recommended anymore. It was 18 years ago when I first started learning small programs. At that time, the Vant documentation introduced the way to download the code package and manually import it statically.

Please refer to the screenshot for the latest introduction of Vant in my company’s small program project:

3, small program page jump between some rules, VUE developed wabApp project, jump route generally use programmic navigation:

this.$router.push({path: "/houseDetails".query: {id: id}});
// Pass parameters are defined in query.
Copy the code

There are four kinds of jumps for small programs:

// Leave the current page and jump to a page in the application. But you cannot jump to the Tabbar page. Use wx.navigateBack to return to the original page.
wx.navigateTo(Object object);

// Close the current page and go to a page in the application. However, jumping to the Tabbar page is not allowed.
wx.redirectTo(Object object);

// Close all pages to open a page within the app
wx.reLaunch(Object object);

// Jump to the tabBar page and close all other non-Tabbar pages
wx.switchTab(Object object);
Copy the code

In the beginning of the development of the homepage, I used bindtap to click the event to bind a method. In the inside of the homepage, I used navigateTo to click the event and did not jump to the page. The next day, I carefully looked at the document and found that the page to jump to was tabBar page. Instead of using navigateTo, use switchTab to jump to 😳.

4. Install the NPM third-party plug-in

Refer to this document: developers.weixin.qq.com/miniprogram…

Specific steps:

NPM install –production

If you want to install moment.js, NPM install moment –save

(3) After installation, go to the menu bar of wechat developer tools -> Tools -> Build NPM, click Execute, and wait for completion.

(4) After the build, there will be a miniprogram_npm directory in the root directory of the project, which contains the installed moment.js plug-in.

Then reference it in utils.js:

// moment format time
import moment from 'moment';
Copy the code

The moment.js API can then be used to format the date data in momentFormat in the global method configuration file utils.js, as shown below:

Function () = function(); this = undefined;

Such as:

keywordChange: app.utils.debounce((e) = > {
    this.setData({ searchKeyword: e.detail });// This is undefined so this line will report an error
    if (app.utils.getByteLen(e.detail) > 3) {
        this.setData({ searchLoaderShow: true}); }},500)

keywordChange: app.utils.debounce(function(e) {
    this.setData({ searchKeyword: e.detail });// Don't use es6's arrow function
    if (app.utils.getByteLen(e.detail) > 3) {
        this.setData({ searchLoaderShow: true}); }},500)

Copy the code

< span style = “font-size: 10.5pt;

You have to start with data-, custom property, data- and then you name the key


<view bindtap="gotoDetails" data-searchType="{{ item.id }}"></view>

Copy the code

// method to get the key-value of the click event
gotoDetails(e){
    let url = '/pages/details/details? id='+ e.currentTarget.dataset.searchtype;
    // There is a hole in the binding event setting parameter, if the parameter name has uppercase letters, the following should be lowercase, otherwise undefined error. For example: data - searchType - > e.c. with our fabrication: urrentTarget. Dataset. SearchType
    wx.navigateTo({
        url: url
    })
}

Copy the code
// You can't put parameters in parentheses like vue projects do<view bindtap="gotoDetails(id)"></view>

Copy the code

7. Error reporting:Wx. switchTab: URL Does not support queryString

TabBar pages do not support URL passing, so you can only use the globalData query parameter in app.js to assign a value to the page to which you want to jump.

Such as from the search page jump to the housing list page, through the app. In the js globalData houseListQuery. SearchKeyword to housing list page spread, refer to the below:

8, make fun of the wechat developer tool version management, really TMD difficult to use, it is better to directly use the command line to operate Git to convenient, with intellij IDEA built-in Git management tool is far from.

Attach a WeChat developer tools version management Settings tutorial: static.oschina.net/news/99140/…

9, wechat small program set as the experience version, can not load data, into the home will play aToast light hintError:Object Object

Baidu search results show that the domain name has been recorded, HTTPS has been configured, SSL certificate of a later version than 1.2, and the server domain name has been configured in the background of small programs

The applet iterates through the object with the wx:for-index attribute


<view wx:for="{{ obj }}" wx:for-item="item"  wx:for-index="key">
    <view class='aside'>{{ key }}</view>
</view>

Copy the code

11, small program custom components some like vUE componentation, such as details page type content structure complex page or there are two or more business page modules have reuse requirements, can be used to achieve custom components, specific tutorials can refer to:

Developers.weixin.qq.com/miniprogram… Blog.csdn.net/qq_41813695…

Note: Custom components cannot use WXS.

12. If the applet needs to perform echarts chart visualization on a dashboard statistics page or detail class page, but there are many Echarts charts that need to be encapsulated, it is best to use the applet’s WebView to achieve this

Specific tutorial can reference: developers.weixin.qq.com/miniprogram… www.jianshu.com/p/292f73512…

For example, I developed a small program for a ToB project in my company 19 years ago. My situation at that time was as follows: the project had already developed the PC side, but the small program had to be developed simultaneously. The details page will have many echarts charts 📈, various types of charts, bar charts 📊, pie charts, line charts, area charts, etc., nearly hundreds of them, which is suitable for webView.

At the beginning, I did not know the concept of WebView. I remember at that time, echarts charts had a special plug-in for small programs, and THEN I was trying to figure out how to encapsulate the four public charts (LINE, Bar, PIE and area chart) that were globally available based on this plug-in. I had no idea for a few days, which was very troublesome. Later, CTO boss told me that this kind of chart page with large data volume can be realized by webView in disguise.

Then I immediately went to see the introduction of WebView in the official document and decided to adopt the technical solution of small program WebView. I only needed to create a new vue mobile terminal project, which was dedicated to serving small program adopting Webview. The project git repository was named “xxx-Weike-charts”. Then the ready-made PC look at the situation page of the business module diagram related code and directory structure, copy the copy to the mobile end of the project on the line, is nothing more than to change a little things.

You can define 9 page pages in the small program, named by the chart business module in the details page, and then click on each module to jump to the corresponding page page of this module, and put all the parameters required by the chart under this module (such as commodity ID), through the URL. Then the webView component in the WXML of the page is dynamically set to SRC. Js to get the query parameter carried when the module is clicked from the detail page. After stitching, setData sets the webviewURL.

For example, the applets detail page of this region profile business module:

When the user clicks, it jumps to the houseDetails_RegionSituation page, and the custom Query parameter is carried over to the houseDetails_RegionSituation page js, The interface URL required by the business module of the above VUE mobile terminal chart project is processed and splicing in setData, and then the SRC attribute is assigned to the WebView, as shown in the following code:

<! -- Graph module using webView component page -- WXML --><view class="page-body">
    <view class="page-section page-section-gap">
        <web-view src="{{ webviewURL }}"></web-view>
    </view>
</view><! -- graph module using webview component page -- js--> data: {id: null.Id / / commodities
    zip: null,},onLoad: function (options) {
        // console.log(options)
        // Get url parameters
        this.setData({
            id: options.id || null.zip: options.zip || null
        });

        let url = 'https://----- Here is your configured business domain name -------/ Situation? id=The ${this.data.id}&zip=The ${this.data.zip}`;
        
        // Situation is the module page name, however you want to define it. This is followed by the Query parameter

        this.setData({
            webviewURL: url
        });
},

Copy the code

The reason why there are 9 chart modules in the project details page, the applet needs to create 9 new pages, because a page page can only put one WebView component, and will overwrite the other components.

Then obtain the query parameters carried by the small program webView SRC jump in the vUE mobile terminal diagram project, and then vUE syntax to obtain query parameters, interface request data, configuration diagram generation instance, the mobile terminal page of the business module diagram data can be normally displayed in the small program. There is no problem with interaction, the logic of the whole process is done.

Remember to also destroy the chart instance when exiting the page to free up memory. This should also consume memory in the applet. The life cycle of a VUE project looks like this:


 beforeDestroy () {
    if(this.myEcharts){
        this.myEcharts.dispose(); }},Copy the code

Specific flow is above these, not complex.

It down and save a lot of work, up nine diagrams of business module, add up to hundred echarts charts, using webview technology solutions, from no to finish after self-test, only three or four days time, I don’t have a headache the trouble with this small program of the custom form to encapsulate implementation requirements, and that there will be a performance issue.

Then share a solution for page performance and interaction optimization: For example, in the detail page of the PC side project, the business modules of the chart add up to 9, and there are nearly 100 Echarts charts in total. If the user enters the page for the first time and loads all the chart interfaces, the DOM structure and JS of so many charts need to be fully rendered, then the browser memory will be very high, and the user will be stuck for a few seconds, and the experience will be poor. Therefore, it was later optimized as: User first entered the page is the default not loading chart of relevant interface, using each chart business module to make folding panel, click on the page module, to request all chart under the module interface and then process the data rendering echarts instance and the DOM structure, fold the destruction of the chart instance release the memory, and only in the first time when loading interface, After folding up and then expand the need to repeat the request interface, so optimized, the details page load time is greatly shortened.

13, Image component default image width 300px, height 225px, ugly, to achieve 100% width, height adaptive effect, use mode=”widthFix” parameter

Refer to the API documentation: developers.weixin.qq.com/miniprogram…

14. Anchor Anchor point positioning, similar to floor navigation, mainly uses the Scroll-into-view attribute of the Scroll-view component

Refer to the tutorial: developers.weixin.qq.com/miniprogram… Blog.csdn.net/weixin_4267…

15, use TXV-Video Tencent video small program plug-in, Tencent video in the small program play function.

【 TXV-Video label scheme 】

1️ : Log on wechat public platform, and then add Tencent video plug-in in the third-party Settings.

2️ discount: Add the following code to app.json

// Version is the version number of Tencent Video plug-in. After I installed it today, I checked the latest updated version is 1.5.2
//provider is the AppID of the small program. You can fill in the AppID of the small program you developed
"plugins": {
    "tencentVideo": {
        "version": "1.5.2"."provider": "wxa75............"}}Copy the code

3️ : Add the following code in the JSON file of the page to be labeled with TXV-Video, such as Tencent video playback function in the details page, then add the following code in the index. Json of the Details directory:

"usingComponents": {
    "navigationBarTitleText": "Details Page"."txv-video": "plugin://tencentVideo/video"
}
Copy the code

4️ discount: Take out the VID in video SRC returned by business interface, the specific logic depends on how to realize it. My code is put up for reference only, it may be a little silly, the technology at that time in 18 and 19 years is still relatively less 😝

For the interface of our project, the video field returns the embed tag, and the PC side vue’s V-HTML instructions are directly rendered out. However, the small program cannot use rich-text to render the embed tag 🤑

// Select SRC from video
let videoSrc;
if (res.data.video.includes("src=")) {
    videoSrc = res.data.video.split('src=') [1].split('allowFullScreen') [0]; 
}
console.log(videoSrc)
// Retrieve the value of VID in videoSrc
let vid;
if (videoSrc.includes("vid=")) {
    vid = videoSrc.split('vid=') [1].split('&auto') [0];
}
this.setData({
    vid: vid
});
console.log(vid)
console.log(this.data.vid)
Copy the code

5️ discount: Then use TXV-video label in WXML, it is over, egg pain is advertising 😒

// PlayerId name is arbitrary, similar to this tag ID, is unique. // If there are multiple business modules in the page that want to play Tencent video, then put multiple TXV-Video tags, pay attention to the playerID of each tag cannot be repeated.<txv-video vid="{{ vid }}" playerid="txvVideo1"></txv-video>
Copy the code

This is the end of the matter, the business function of playing Tencent video has been completed, as for the product needs to have a number of videos/video list, if you want to do a dynamic switch, you slowly grope for it, it should not be difficult. Small program play Tencent video solution, it seems that the most convenient is to use TXV-video label, and then pass the VID value, you can achieve the function of playing Tencent video, better than the following video component scheme, video component scheme is too troublesome, and has passed a long time, belongs to a method of cheating.

[Video component to realize the scheme of playing Tencent video]

The specific process can refer to this big guy’s tutorial: blog.csdn.net/qq_41629498…

The logic of taking the VID value in the front is the same, except that the interface vv.video.qq.com should be sent later, and the complete video URL should be cut and splice according to the returned fields, which is just such a logic.

Note: I failed to complete this project successfully, because I got stuck in the step of configuring the server domain name.

Tcb-api.tencentcloudapi.com, https://vv.video.q… I’ve added and configured these two domains,

But when they request interface error: vv.video.qq.com is not in the following request legal domain name list, please refer to the document: developers.weixin.qq.com/miniprogram…

At first, I thought it was to configure the server domain name, small program has cache, need to wait for 10 minutes, but later still not, do not hesitate to give up the scheme decisively.

16. Click on the image to preview the larger image, and use the general details page for rotation

Reference: developers.weixin.qq.com/miniprogram…

<swiper indicator-dots  circular indicator-active-color="#fff" current wx-if="{{ !housePhotoNoDataShow }}">
    <block wx:for="{{ housePhotoItem }}" wx:for-item="item" wx:key="index">
        <swiper-item>
            <image src='{{ item }}' lazy-load mode="aspectFill" data-index='{{index}}' bindtap='previewImg'></image>
        </swiper-item>
    </block>
</swiper>

Copy the code
previewImg(e) {
    var currentImgIndex = e.currentTarget.dataset.index;
    var imgArr = this.data.housePhotoItem;
    // console.log(currentImgIndex, imgArr);
    wx.previewImage({
        current: imgArr[currentImgIndex],     // The current image address
        urls: imgArr,               // An array of all images to preview
        success: function (res) {
            console.log(res)
        },
        fail: function (res) {
            console.log(res)
        },
        complete: function (res) {
            console.log(res)
        },
    })
},
Copy the code

17. App.js added user friendly prompt for update online version (for prompt prompt of new version update when hot startup, and automatic download of update when cold startup)

Refer to the official documentation: developers.weixin.qq.com/miniprogram…

App({
    onLaunch: function (options) {
        // Get applet update mechanism compatibility
        if (wx.canIUse('getUpdateManager')) {
            const updateManager = wx.getUpdateManager();

            // Listen to the event to check the update result. Wechat will automatically check for updates when the small program starts cold, without being triggered by the developer.
            updateManager.onCheckForUpdate(function (res) {
                // Request a callback for the new version information
                console.log(res.hasUpdate)
            });

            // There is a version update event in the listening applet. The client automatically triggers the download (without triggering by the developer), and the download is successfully triggered
            updateManager.onUpdateReady(function () {
                wx.showModal({
                    title: 'New version update prompt ~'.content: 'The new version of this applet is ready. Do you want to restart the application? '.success: function (res) {
                        if (res.confirm) {
                            // The new version has been downloaded. Call applyUpdate to apply the new version and restart
                            updateManager.applyUpdate()
                        }
                    }
                });
            });

            // Listen for applets update failure event. There is a new version of the small program. The client automatically triggers the download (no need to be triggered by the developer), and the download fails (possibly due to network reasons)
            updateManager.onUpdateFailed(function () {
                // Failed to download the new version
                wx.showModal({
                    title: 'There is a new version.'.content: 'The latest version of this small program has been online ~, please delete the current small program in the small program list, search keywords to open this small program to experience the latest version of yo ~',})}); }else {
            Prompt the user to try your applet on the latest version of the client
            wx.showModal({
                title: 'Hint:'.content: 'The current wechat version is too early to use the mini program normally. Please upgrade to the latest wechat version and try again. '})}}})Copy the code

18. Custom components do not inherit the app. WXSS global style by default, but you can set addGlobalClass: True in the js of the custom component

Refer to the official documentation: developers.weixin.qq.com/miniprogram…

Including the scene of using Ali iconfont icon library, I encountered the situation that icon could not be displayed all the time. Wechat open community and Baidu searched a lot of articles, but it was not the problem introduced by Base64, nor the cross-domain problem of AT.alicdn.com. Then I suddenly remembered the style inheritance problem from the defined component, and finally jumped the hole. Alas, another wasted morning 🤑……

Component({
    options: {
        addGlobalClass: true.// The parent component style or app.wxSS global style can be inherited}})Copy the code

19. Records from 2020 to December: After more than a year and a half time, again start to make the small application project recently, on small company for nearly three years by the end of the 19th layoffs dissolution of the team, 20 years earlier in the castle to do for several months and dancing, to the middle of the goose factory do outsourcing, in binhai headquarters thief, recently took over a goose for use within the plant small programs, to develop new demand, Recently, wechat developer tool has updated a lot of functions, more and more like vscode, it has the function of automatically generating skeleton screen, it is amazing.

Usage can refer to official document, developers.weixin.qq.com/miniprogram…