Writing in the front

Because micro channel small program claims to solve the front-end programmer headache compatibility problem, only need to code according to Tencent’s official set of rules can meet different terminal needs. Therefore, IN the second half of last year, I realized a project for internal use of our company with wechat mini program (currently 700+ users). Here are some experiences I summed up in the process of exploring, paving the way for the students behind to go home early to accompany their wives and children.

You will learn:

  1. How to use custom Tabbar and permission control
  2. How to use the Echarts charting plug-in
  3. How to subcontract when the program size exceeds the limit
  4. How to use the vantUI component to solve the pop-up layer slide through the page scroll
  5. Custom headers and scrolling pages emerge at the top
  6. How to implement automatic update and manual update scheme
  7. Internal use software requires login, how to pass the audit

Other pits

  • Why not update views after setting data using wepy
  • How do I access my own methods in WEpy Methods
  • Applets may be named against the rules
  • Date initialization pit on iOS

1 How to use custom Tabbar and permission control

Those of you who have used native Tabbars know that they are ugly and that it is impossible to customize some of the styles. Most apps will eventually require custom tabbars. The rule is to lose the official link first

Use steps:

Copy the custom-tab-bar file in the official demo to the root directory

The wepy framework I used is copied to the SRC directory as shown in the figure below. Yes, the custom tabbar part needs to use the native writing method, and the other business pages use the Wepy framework.

Entry file app.json enables custom tabbar

The Wepy framework is in the app.wpy Config object

It is necessary that the pagePath in the list be the directory of your own page. All other attributes can be removed because the specific tabbar styles (such as images and colors) must be set in the custom custom tab-bar.

"TabBar ": {"custom": true, //"color": "#7A7E83", //"selectedColor": "# 3CC51F ",// Write awesome here annotated //"borderStyle": "black",// Write awesome here annotated //"backgroundColor": "# FFFFFF ",// Write awesome here annotated "list": [{"pagePath": "index/index", "iconPath": "image/icon_component.png",// }, {"pagePath": "index/index2", "iconPath": "index/index2", "iconPath": "icon_component_hl.png "," icon_component_hl.png ", "iconPath": SelectedIconPath: "image/ icon_api_hl.png ", "image/ icon_api_hl.png ", "selectedIconPath": "image/ icon_api_hl.png ", "image/icon_API. "Interface "// here write the function can comment}]},Copy the code

Go back to customizing custom-tab-bar/index.js

There is the following code:

Component({data: {selected: 0,// select subscript color: "#7A7E83",// select subscript color: "#3cc51f",// select subscript color: "#3cc51f",// select subscript color: "#3cc51f",// [{ pagePath: "/index/index", iconPath: "/image/icon_component.png", selectedIconPath: "/image/ icon_component_hl.png ", text: "component ", {pagePath: "/index/index2", iconPath: "/image/ icon_api.png ", selectedIconPath: "/image/ icon_API_hl.png ", text: "interface"}]}, attached() {}, methods: {switchTab(e) {const data = e.currenttarget. Dataset const URL = data.path wx.switchTab({url}) //this.setData({Annotation out this three lines // selected: data.index //}) } } })Copy the code

The this.setData() method is commented out because jumping to a TAB page also sets data once, so you can avoid flashing data repeatedly.

Add code for each TAB page life cycle show

In the wepy framework is the onShow method. Gets the current page object this.$wxPage

onShow() { if (typeof this.$wxpage.getTabBar === 'function' && this.$wxpage.getTabBar()) { This.$wxPage.gettabbar ().setData({selected: 0})}}Copy the code

As you can see, every time you enter a TAB page, you get the bar object of the current page (the tabbar object is not the same in each TAB page, it is a new object) and set selected. So comment out the setData method in the switchTab method above because it duplicates.

Menu upper right corner digital info implementation and update

  1. Add the infoNum property to the list array (for menu items required).
  2. Conditionally render infoNum in WXML code (display only if it has a value greater than 0).
  3. Each TAB page shows the life cycle to get the info number after setData.
This.$wxPage.gettabbar ().setData({['list[1].infonum ']: infoNum})Copy the code

[‘list[1].infonum ‘] update multi-layer objects

Control menu items according to the logged in role

I believe there are many students also have this demand, according to the different login user, see the bottom menu is also different, such as: administrator. The implementation is very similar to info

  1. Add the property show to list array
  2. Conditionally add show and hide classnames to the WX :for loop in the WXML code
  3. After login, get the user permission list and determine which items to show or hide
  4. Call the method to update the bar instance’s data

For convenience, create methods in custom-tab-bar/index.js methods and call them on each TAB page: This.$wxPage.gettabBar ().yourfuncName (Balabala), note each bar page, because it says that each TAB page bar instance is independent.

Native pages getTabBar instances directly from this.gettabbar ().

Due to the limited space, some details are not finished, please leave comments or contact me directly if you have requirements.

How to use the Echarts charting plug-in

Using diagrams in small programs is a very common requirement, but there are already mature Echarts components. Use method is very simple, according to the rules first dump official link according to the official document configuration, but need to pay attention to the point:

  1. The original echarts.js is relatively large, and the package size of small programs is limited. It is recommended to go to the echarts website to pack as needed
  2. You need to write in style:
ec-canvas {
  width: 100%;
  height: 100%;
}
Copy the code

3. Preview the Echarts chart in the wechat development tool and it shows that there is a problem, but it does not appear on the real phone

How to subcontract when the program size exceeds the limit

Small program to ensure that users quickly open the program, there is a good user experience. Therefore, the size of the small program is limited (a total of no more than 20M, each package no more than 2M), but as the program becomes more and more complex, more and more pages, we will not be able to exceed the limit, fortunately, the official gave a subcontracting scheme. Official link according to rules

  • In simple terms, the main pages (those associated with Tabbar) are first downloaded to the client and displayed – the main package
  • Other secondary pages (details) can be downloaded and displayed as needed. – the subcontract

There can be any number of subcontracting, so that the size of each package can be effectively controlled. Core configuration code:

app.js/app.wepy

Pages: [// main package TAB 'pages/index', 'pages/bill', 'pages/mgMenu', 'pages/my',], subPackages: [{// subPackages: [// main package TAB 'pages/index', 'Pages /bill', 'pages/mgMenu',' Pages /my',] 'subPackage1',//subPackage1 = subPackage1 ["pages/login", // login" pages/billDetail", // bill details "pages/shopDetail", // product application]},Copy the code

Note: Each time you add a page, add the page path to the pages of the corresponding package

Speaking of the size of small programs, static files in the project such as (open source JS, fonts, pictures, videos) can be thrown into the CDN, on the one hand to reduce the package size, on the other hand to increase the speed of reading. CDN can be used for charging, such as Ali, or free CDN, such as BootCDN, JsDeliVR, UNPKG, etc. If you are interested I will write a separate white whoring CDN article.

How do I use the vantUI component

In the current trend of rapid iteration, UI library is very important, I prefer the open source vantUI, of course, other UI library is also very good, see personal preference. Follow the rules and post the official link

Here are some of the things I learned using vant components:

  1. I chose to download the compiled component code, and copy any component that the project needs into its own components, click here

The downside of using this method is that the components you use need to be copied if they depend on other components. Json for example,

the index. Json component is as follows:

{ "component": true, "usingComponents": { "van-icon": ".. /icon/index", "van-loading": ".. /loading/index" } }Copy the code

The

component also depends on the

and

components. In this case, we can copy the

and

components into our components directory.




2. Before using it in a page, configure it in usingComponents, and the path is relative to each other. Do not use @ as import, but use.. To find a path.

usingComponents: { "van-action-sheet": ".. /components/lib/action-sheet/index", "van-toast": ".. /components/lib/toast/index", "van-picker": ".. /components/lib/picker/index", "van-popup": ".. /components/lib/popup/index", "van-search": ".. /components/lib/search/index" },Copy the code

Popup prevents the page from scrolling method

When we use the Popup layer to Popup the time picker, or picker, etc. In this case, when the content of the layer is rolled up, the content of the main page at the bottom will also slide, affecting user operations. We can use

to wrap the main content. By default, scroll-y=”true”, and set the property of scroll-y=”{{false}}” when the layer is rolled up.

Through variable control:

<scroll-view scroll-y="{{! noScroll}}" bindscroll="scrol">

Set noScroll to true or “(empty string) when pop-up layer is shown or hidden. Note that the string “false” has a Boolean value of true

In addition, if the page has only one screen and no scrolling is required, you can use the config command to set disableScroll: false

How does the software for internal use pass the audit

Most of the internal software is to enter the program must log in to continue to use, but does not conform to the official design specifications of small programs. Before, our company jumped to the login page after entering the page, but the result was not approved. If your page is less secure, you can default to the home page and menu, but the data is still thereWhite space. Hint at key pointsVisible after login, our company small program visitor mode is as follows:

If your software confidentiality is strong, you must authorize users to log in, you can provide an experience account to the audit staff when launching the audit, and indicate that the software is only for enterprise content.

Custom head and slide surfaced at the top

Custom headers are also a common requirement. How do I implement this

  1. Page Config SettingsNavigationStyle: 'custom'
  2. Add code to WXML
<view class="cus-head" hidden="{{! ShowCusHead}" style="height:{{cusHead}}"></view> <view class="head-title" style="top:{{titleTop}}">Copy the code

Cus-head: Custom head block fixed layout.

Head-title: fixed layout of title, ensuring that z-index is above cus-head, top value should be the same as capsule, and line-height should be highly consistent with capsule. Here is the API for getting the capsule:

Const res = wx. GetMenuButtonBoundingClientRect () the console. The log (res) height) / / access capsule height. The console log (res) top) / / access capsule top valueCopy the code

CusHead: customized head, the height should be greater than the height of the capsule, can be adjusted according to your own needs.

ShowCusHead: Control show hide, show when scrolling to a certain point, hide when rolling back to the top

  1. Add a scroll listener function
Scroll (e) {const top = e.dail.scrollTop; if (top >= 10) { this.showCusHead = true; } else { this.showCusHead = false; } this.$apply(); },Copy the code

How to implement automatic update and the alternative plan of manual update when automatic update

Add the following code to app.wpy or app.js lifecycle show/onLaunch. I can write it as a function and call it directly.

Complete code reference:

If (wx.caniUse ('getUpdateManager')) {const updateManager = wx.getupDatemanager () //1. . Check the small program for the new version released updateManager onCheckForUpdate (function (res) {/ / request callback if the new version information (res) hasUpdate) {/ / 2. Small program is the new version, download the new version is silent, prepare for update updateManager. OnUpdateReady (function () {wx. ShowModal ({title: 'updates, content: 'The new version is ready. Do you want to restart the application? ', success: function (res) { if (res.confirm) { //3. Download the new version of good, call applyUpdate application. The new version and restart updateManager applyUpdate ()} else if (res) cancel) {/ / forced updates if required, are given second popup window, if you don't need, Wx. showModal({title: 'warm tip ', content:' This version update involves the addition of new functions, the old version can not be accessed normally oh ~', success: function ( res) { self.autoUpdate() return; If (res.confirm) {// The new version has been downloaded, Call applyUpdate to apply the new version and restart updatemanager.applyUpdate ()} else if (res.cancel) {// Return to version update prompt self.autoupDate ()}})} }})}) updateManager. OnUpdateFailed (function () {/ / new version download failure wx. ShowModal ({title: 'updates, content: })})}) #} else {// If you want users to experience your applet on the latest version of the client, you can prompt wx.showmodal ({title: 'Warning ', content:' The current wechat version is too early to use this function, please upgrade to the latest wechat version and try again. '})}Copy the code

Alternate update plan

In the small program page such as the personal center, add the version number, add the click event to the version number, click and call the above method again, manually update.

Other pits

After the Wepy framework sets the data, it manually calls the this.$applay() view to update it

I am very unfriendly to the students who use Vue. I often forget to write and the view is not updated. I think there is a bug

wepy methodsCannot pass throughthis.funnameAccess to their

  • To access it directly with this.funname, you need to write it in the outermost layer (same lifecycle level)
  • If stubbornly direct call can use this. The methods. FuncName. Call (this)

New Date error on iOS

On iOS, new Date(‘2021-1-1 12:00:00’) is not recognized as a string by -connection. Replace (/\-/g, ‘/’) can be replaced with ‘/’.

Applets may be named against the rules

The name of the small program online is very key, the name is a drainage tool to some extent, but the small program official name has very strict regulations, if not in accordance with the provisions of the name, the online will be forcibly removed. Our company took the term “electricity” and asked to change the name, because the term is government and private companies can’t use it. The official connection

Thank you

Since this is the first time to write this kind of technical article, there are many shortcomings, thank you for reading the last, if this article is helpful to you, please don’t forget to give me a like, comment.