Applets are now divided into native and framework development.

After comparing the relative advantages and disadvantages, I still prefer to use the framework, mainly because the development efficiency is really much higher than the original, and there are not so many pits in the actual practice, basically the small program can achieve things uni-App can also be well adapted. Here are some of the problems I encountered as a summary of my experience in uni-App development.

The global problem

Small program subcontracting

The size of each subcontract of wechat mini program is 2M, and the total volume cannot exceed 16M.

Subcontracting of small programs should be the first consideration, after all, who knows whether the project will be more and more features, and uni-App packaging into small programs will be larger than native development, it will be easier to reach the ceiling of 2M. In the end, because subcontracting was not considered at the beginning, it would be a lot of work to change the directory structure and then subcontracting.

  • Uni-app Subcontracting instructions
  • Specific configuration of uni-APP subcontracting

Cross-platform issues

  1. First of all, at the beginning of the project scheme, we should make clear which end we need to package to. We should first go to the official document to see the vUE syntax feature support table, confirm that the syntax we will use is not supported by the corresponding end, and there is no alternative solution, so as to avoid bugs and locating problems.

  2. Secondly, many people may reference some component libraries during development, such as WeUI, Vant, etc. If you only need to consider one end, you can safely introduce it. If the project has the possibility of implementing cross-ends in the future, it is recommended to rewrite all the required components yourself. If you don’t know how to implement it and need reference code, you can go to the uni-App plugin market to see if there is a suitable one, take the core code down and change it.

Project creation

Uni-app’s official documentation also makes clear the difference between cli creation and visual interface creation. In practice, both methods are similar. The official visual interface has a lot of shortcut syntax is quite convenient, especially favorite is the image tag can directly identify the local image path. But parts of the editor were not so friendly, and in the end vscode was preferred.

One of the most outrageous issues is that the official documentation says that cli builds can be updated directly, and that NPM updates can be done by upgrading the compiler, and then months later attempts to update them with a small program to official the new features. After the update, the project directly reported an error that could not be executed, with more error information and difficult to solve. This is a risk with uni-app.

Project package

When sending the package to the production version, be sure to upload the package running the build command. The package size will be much smaller.

npm run build:mp-weixin
Copy the code

The question icon

Small program icon and picture as far as possible to use the network address, in the real machine has occasionally can not load the situation, is small program official write bug, in the recent to repair. And using the network address does not take up the space of the applet package.

Summary of development experience

Some of the following development lessons are native to small programs, but the implementation of Uni-app is mentioned here in passing. In general, any API that starts with wx. In the applet side of uni-App can use WX directly. If the current uni-App framework supports the features of the current applets.

Applet custom title bar

If you want to implement a title bar similar to the one below, just set it in pages. Json

{
    "path": "test",
    "style": {
        "navigationStyle": "custom"
    }
}
Copy the code

Then the title bar in the page will be hidden, and then you can put your own title bar components into the page, it is worth mentioning that the following method can obtain the height of the capsule and the current position from the top, you can solve the title bar adaptation problem.

onReady () {
    let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
    let menuHeight = menuButtonInfo.height  
    let menuTop = menuButtonInfo.top
}

Copy the code

TextArea hierarchy problem

Address the problem

Because of the bug of the small program, the text of the textArea will always be in the top layer and cannot be blocked. If there is another pop-up layer above the textArea (such as the pop-up window), you need to empty the textArea first, or directly use v-if to hide the entire textArea. And then you recover.

Picture view control

In the small program, if you want to click the picture to preview the picture and achieve the effect similar to the picture viewer in wechat chat, you need to use the following methods:

Wx.previewimage ({current: this.baseimgURL + this.userdata.qrcode, // current image address urls: [this.baseimgurl + this.userdata.qrcode], // All images to preview the address set array form SUCCESS: function(res) {}, fail: function(res) {}, complete: function(res) {} });Copy the code

To obtain authorization

Obtain wechat login authorization can be directly invoked by Wx. authorize to obtain wechat login authorization. However, the wx.authorize({scope: “scope.userinfo “}) that obtains user information does not pop up the authorization window. It must be called using the following method, silent authorization, which makes it difficult to distinguish unauthorized from unauthorized during developer platform and real machine testing. And wechat official also explained that this method will be abandoned later, there is a high risk of use.

<button open-type=" authorize" @getUserInfo ="authorize" > </button>Copy the code

It is generally recommended not to refresh the page repeatedly, but only to obtain the data displayed during the first loading in the onLoad, which is convenient to re-call the onload event of the page after the authorized login, so that the method executed during the first loading of the page can be re-executed

    let page = getCurrentPages().pop()
    let option = page.options
    page.onLoad(option)
Copy the code

webview

The webview of the applet will take up the entire width and height, automatically covering the entire page. Methods to support partial applets. The most important thing is that the domain name of the iframe also needs to be configured to the domain name whitelist. Developers.weixin.qq.com/miniprogram…

v-html

If you need rich text in UNI-App using V-HTML directly, the applet side also supports it and automatically converts it to tags in the applet. If you need to style the returned HTML string, it is recommended to use a re for matching.

Encapsulation method of an interface

If you want to implement axios’ interceptor function, you need to manually encapsulate the request method of the interface. You can also encapsulate uni-App’s plug-in market

Export default {_this: this config: {/ / main baseUrl URL: "https://api.vc.bilibili.com/link_setting/", / / just for example the header: { 'Content-Type': 'application/json; charset=UTF-8' }, data: {}, method: "GET", dataType: Parse */ responseType: "json", /* responseType: "text", success() {}, fail() {}, complete() {} }, interceptor: { request: (config) => { let token = '' if (token) { config.header.token = token } return config }, response: (Response) => {// When debugging, you can print all returns, Return // console.log(response)}}, request(options = {}, iterceptor = {request: undefined, response: undefined }) { options.baseUrl = options.baseUrl || this.config.baseUrl options.dataType = options.dataType || this.config.dataType options.url = options.baseUrl + options.url options.data = options.data || {} options.method = options.method || this.config.method options.header = options.header || this.config.header let interceptorRequest = iterceptor.request || this.interceptor.request let interceptorResponse = iterceptor.response || this.interceptor.response return new Promise((resolve, reject) => { let _config = null options.complete = (response) => { let statusCode = response.statusCode response.config = _config if (interceptorResponse) {interceptorResponse(response)} if (statusCode === 200) {// resolve(response); } else { reject(response) } } _config = Object.assign({}, this.config, options) if (interceptorRequest) { interceptorRequest(_config) } uni.request(_config); }); }}Copy the code

The following is a reference to the js file encapsulated above

import http from './interface' export const test = (data) => { return http.request({ url: 'ajax/echo/text? name=uni-app', dataType: 'json', data, }) }Copy the code

Map considerations

  • Map related interface preview must be carried out in the real machine, do not just preview in wechat developer tools and then think that the function is finished. In particular, preview it on both ios and Android.

  • If you need to listen for regionChange events and then perform operations on the map render, remember not to put methods that change the map position in the listening event. Otherwise it will create an endless loop. And a lot of

      regionchange(e) {
        if(e.causedBy==='drag'){
          this.updatedMapCenter()
        }
        if (this.firstLoadMap||e.causedBy==='update'||e.causedBy==='drag') {
          return false
        }
        this.getInstanceMapData()
      },
Copy the code

Shared pages

By default, the page of the applet does not have a share button. If you click on the share button in the upper right corner, it will turn gray. If the page needs to enable the sharing function, add this event

onShareAppMessage(ops){ console.log(this.selectedApartDetail); Return {title: 'Click to view business department ', path: /pagesHome/home, // click to share message is opened page imageUrl: '.. /logo.png' } }Copy the code

If global Settings are required, you can dynamically bind onShareAppMessage events to all pages in app.vue via onAppRoute time.

wx.onAppRoute(function (res) { let pages = getCurrentPages(), View = pages[pages.length-1] if (view) {let rewriteState = true for(let item of notRewirte){ if(view.route.indexOf(item)! ==-1){ rewriteState = false break } } if (rewriteState) { view.onShareAppMessage = (a,b,c)=>{ let returnPath = '' return  { title: 'test', path: returnPath, imageUrl: '.. /.. /.. /static/login/log.png' }; }}}})Copy the code

Save the page as a picture

One of the most common requirements is to save the entire page as an image, and then share the image with friends to facilitate the diversion of the small application. The main idea is to save the page as canvas

<canvas canvas-id="myCanvas" class="canvasIs"/> // omit some code const CTX = wx.createcanvasContext ('myCanvas'); const grd = ctx.createLinearGradient(0, 0, 0, 0); grd.addColorStop(0, '#fff'); grd.addColorStop(0, '#fff'); ctx.setFillStyle(grd); // Color the created Canvans context if fillStyle is not set, the default color is black. ctx.fillRect(0, 0, 300, 556); ctx.drawImage(this.data.img, 0, 0, 300, 556); ctx.setFontSize(50); Ctx.settextalign ('center'); SetFillStyle ("#333333"); ctx.setfillstyle ("#333333"); Ctx. fillText(" required text ", 210, 285); ctx.draw();Copy the code

Before exporting pictures, you need to obtain the permission of the applet to save pictures

Wx.opensetting ({// Enter the applet authorization Settings page success(settingData) {console.log(settingData) if (settingdata authSetting [' scope. WritePhotosAlbum ']) {/ / authorized users open the save image switch wx. SaveImageToPhotosAlbum ({filePath: BenUrl, success: function (data) {},})Copy the code

Then use canvasToTempFilePath to export the canvas as an image

Wx. CanvasToTempFilePath ({x: 0, y: 0, width: 300, destWidth: 600, destHeight: 1112, canvasId: 'myCanvas', success: function(res) { wx.saveImageToPhotosAlbum({ filePath: res.tempFilePath, success: function(res) { //console.log(res); Wx.hideloading () wx.showtoast ({title: 'save successfully ',})}, fail: function(err) {}})}})Copy the code

So much for now, I will continue to add if I think of it. If there is any place that is not clear, please ask me. Give it a thumbs up if you like. Thanks.