1. Introduction

Wechat mini program developed based on van and MPvue recorded the technology selection before development, how to build the environment during development, start projects, step on pits, etc.

2. Demand

Fill out expense report

Page 2.1.

  • The login
  • My. – Personal information
  • Home page

Nav navigation, fill in the log, modify the log, fill in the expense report, expense report review, export the log to the designated mailbox, select the date to view my log

2.2. Front-end technology selection

2.2.1. Framework



The above image is from a technical selection article in Nuggets.



I choose thempvueHowever, the most recent GitHub update was a year ago, and the team has not maintained much. This issue also needs to be noted.

Official website: github.com/Meituan-Dia… Mpvue (see Github address) is a front-end framework for developing applets using vue.js. The framework is based on vue. js core, and MPvue modifies the runtime and Compiler implementation of vue. js to enable it to run in the environment of small programs, thus introducing a whole set of vue. js development experience for small program development. Using MPVue to develop applets, you gain the following capabilities based on the applets technical architecture:

  • Radical componentized development capabilities: improved code reuse
  • The completeVue.jsDevelopment experience
  • convenientVuexData management solution: Easy to build complex applications
  • quickwebpackBuild mechanism: custom build strategy, hotReload during development
  • Support for using NPM external dependencies
  • useVue.jsCommand line tool vue-CLI quickly initializes the project
  • H5 code conversion ability to compile into small program object code

2.2.2. UI components

Choose a suitable oneUIComponents that help us develop projects quickly

Making website: Github.com/youzan/vant…

Official documents: Youzan. Making. IO/vant weapp /…

Scan the small program QR code below to experience the sample component library:

  • throughmpvueHow does the generated project use the likesvanUI components, and it will display properly?

After importing the UI components, we can test them in the project book. Before that, we need to package the project to make the UI components work, that is, we need to open the terminal and run the NPM run build in the root directory of the project, so that the Vant UI components will work properly in the page

2.2.3. Front-end and back-end communication

Fly: github.com/wendux/fly a promising, request-forwarding, powerful HTTP request library that supports all JavaScript runtime environments. This allows you to reuse as much code as possible across multiple ends. Currently, Fly.js supports Node.js, wechat applets, Weex, React Native, Quick App and browsers, all of which have different JavaScript runtime.

Introduction to the

Fly.js is a promise based, lightweight and powerful Javascript HTTP web library with the following features:

  1. Provide a unified Promise API.
  2. Lightweight and very lightweight in the browser environment.
  3. Supports a variety of JavaScript runtime environments
  4. Support for request/response interceptors.
  5. Automatically convert JSON data.
  6. Supports switching of the underlying Http Engine, easily adapted to various operating environments.
  7. Browser-side support for global Ajax interception.
  8. H5 pages, when embedded in Native apps, support forwarding HTTP requests to Native. Support direct request for images.

Positioning and objectives

Fly is positioned to be the ultimate solution for Javascript HTTP requests. That said, Fly can run on any environment that can execute Javascript, as long as it has the ability to access the web, providing a unified API.

website

For detailed documentation, please go to Flyio’s official website. Fly is used in HTTP requests on the official website. In order to facilitate the verification of fly functions and features, the official website introduces fly globally. You can directly verify fly by opening the console on the official website.

The installation

NPM install flyio NPM install flyio<script src="https://unpkg.com/flyio/dist/fly.min.js"></script>UMD (browser) https://unpkg.com/flyio/dist/umd/fly.umd.min.jsCopy the code

2.3. Selection of server framework technology

Nodejs

3. Get started

This article assumes that you know neither vUE nor applets, so if you’re too slow, skip ahead.

3.1. Initialize an MPVue project

Node.js is required for modern front-end development frameworks and environments. If not, download nodeJS and install it. Then open the command line tool:

$Node -v v8.9.0 $NPM -v 5.6.0 # 2. Due to reasons known to all, can consider to switch the source to the taobao source $NPM registry https://registry.npm.taobao.org/ # 3. $NPM install --global [email protected] # 4. $NPM install --global [email protected] # 4. $vue init mpvue/ mpvue-quickStart my-project # 5. $CD my-project $NPM install $NPM run devCopy the code

With the successful echo, you can see that there is a local dist directory, which contains the generated applet code.

3.2. Build a development environment for small programs

Small program itself has a special wechat developer tools, the latest version of the download address. This step is relatively simple, follow the instructions step by step to install, and then use wechat to scan the TWO-DIMENSIONAL code login. So far the small program development environment is almost complete.

3.3. Debug and develop MPVue

Select the applets and fill in the required information:

  • Project directory: The project directory you just created (non-dist directory)
  • AppID: if not, you can click to experience “small program”, which only affects whether you can debug the real machine.
  • Project name.

As shown in figure:



Click “OK” button will jump to the official development page, click “Editor” button, close the built-in small program editor. Then, as shown below:



At this point, the wholempvueThe project is already running.

Open it in your own editor (or IDE)my-projectIn thesrcTry the code in the directory as an example:

Here we go. Over and out.

3.4. Subcontracting mechanism2018.7.23 +

After mpvue-loader 1.1.2-RC.2, the file generation structure after build is optimized, and the generated directory structure retains the directory structure under the source folder, which is conducive to the support of subcontracting.

3.5. Webpack configuration

Matters needing attention

  1. The new page needs to be re-creatednpm run devTo compile

Warm prompt

Before developing small programs, the first step, need to prepare the computer development environment > node, > NPM, > git, through the > git tool to create a new project, clone the existing code. Step 2, install wechat developer tools, such as we usually debug code in the browser console, wechat small program is through the developer tools debugging code. If it is a new project, click Create in developer Tools. If it is an existing project, click Import. Step 3, Step 4, Step 5, Step 6,

4. Develop code

I developed the code is based on MPvue + van, new page need NPM run dev restart record some commonly used coding, and matters needing attention open source code reference:

  • Netease Yan Xuan Mall based on MPVUE

4.1. mpvue

4.1.1. For loop nesting

<! Index and itemIndex must be specified and their aliases cannot be the same.<template>
    <ul v-for="(card, index) in list">
        <li v-for="(item, itemIndex) in card">
            {{item.value}}
        </li>
    </ul>
</template>
Copy the code

4.1.2. Page Hopping

Applets do not support routing, so, NavigateTo ()

This. Router. Push –>wx.navigateTo()

This. NavigateTo ()

this.router.replace–> wx.relaunch ()// Open a new page to get the current page address this.$route.fullPath–>getCurrentPages()[0].route

4.1.3. Form bidirectional data binding and event binding

An error is reported when using an mpvue such as label=”{{name}}”

<van-cell-group> <van-field label=" userinfo.name ":value=" userinfo.name" placeholder=" please input user name" V-bind :border="false" @change="onChange($event,'name')" /> <van-field label=" password" :value="userInfo. Password "placeholder=" v-bind:border="false" bind:change="onChange($event,'password')" /> </van-cell-group>Copy the code

4.1. How to design mock data and real interface

4.2. The API encapsulation

Set the first loading page

At the compile site, you just need to set the path of the page, check “use the above criteria to compile”, if the page needs parameters, then you can also upload parameters. This launches the page you set up. The first page load of the small program can be set in app.json. The first page is the first page loaded

Later consider adding the startup page (the first time open small program will load) = “login page =” home page

4.3. Introduce aliyun icon

Instead of introducing aliyun ICONS, use local static images instead.

Note: Remember to delete useless files, otherwise the phone preview will show a blank screen, because of an error.

Because there is no document small program, I introduced the ali cloud icon, there is a document. The getElementsByTagName code,

This problem occurs when you get to the demo version. /static/iconfont/ iconfont +demo.html…. Caused by these unrelated documents; The iconfont folder is as follows

4.4. Redirect route and route transmission parameters

  • The list page passes parameters to the detail page
// List page
 /** * jump to the reimbursement details page */
reimbursementDetail(id) {
  // The details page needs to be introduced in app.json
  let url = `.. /reimbursementdetail/main? id=${id}`;
  wx.navigateTo({url});
}
// Details page
mounted() {
    this.id = this.$root.$mp.query.id; // Request the detail page interface by ID
},
Copy the code

4.5. Customize the Nav-bar header

Nav-bar can also be customized in applets, but it is not necessary, as applets have their own headers

4.6. Dynamically set title

wx.setNavigationBarTitle({
      title: "Log in to XX Management System"
});
Copy the code

4.7. Too much data in cyclic rendering is stuck

Scroll through the virtual DOM

5. Common problems with applets

WeChat open community communication: developers.weixin.qq.com/community/d…

5.1. The API request

5.2. Compatibility with the base library

5.3. Different page transfer methods

5.4. Cross-domain problems

Console, if the following is displayed, is a cross-domain problem

 http://www.mxnzp.com is not in the following list of legitimate request domain names,Please refer to the documentation: HTTPS://developers.weixin.qq.com/miniprogram/dev/framework/ability/network.html
Copy the code

Skipping domain name verification

In the wechat developer tool, you can temporarily enable the development environment not to verify the requested domain name, TLS version, and HTTPS certificate, skipping the server domain name verification. In this case, the server domain name will not be verified in the wechat developer tool or when the mobile phone is in debug mode. After the server domain name is configured successfully, you are advised to disable this option and test the server domain name on each platform to ensure that the server domain name is correctly configured.

If a request can be sent when debugging mode is enabled but cannot be sent when debugging mode is disabled is displayed on the mobile phone, check whether domain name verification is skipped and whether the server domain name and certificate are correctly configured.

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

network

Please be aware of the following issues when using web-based apis in your mini-program/mini-game.

1. Configure the server domain name

Each wechat mini program needs to set up a communication domain name in advance, and the mini program can only communicate with the designated domain name. The options include ordinary HTTPS request (wx.request), uploadFile (wx.uploadfile), downloadFile (wx.downloadfile), and WebSocket communication (wx.connectsocket). As of base library 2.4.0, network interfaces are allowed to communicate with LAN IP, but be careful not to communicate with native IP. As of 2.7.0, UDP communication is provided (wx.createudpsocket).

The configuration process

Note Configure the server domain name in the “Applet Background – Development – Development Settings – Server Domain name” area. Note the following when configuring the server domain name:

  • Domain name onlyhttps (wx.request,wx.uploadFile,wx.downloadFile) andwss (wx.connectSocket) agreement;
  • Domain names cannot use IP addresses (except small program LAN IP) or localhost;
  • You can configure a port, such as MyServer.com :8080, but only requests can be sent to myServer.com :8080. If you contact myserver.com, https://myserver.c… The URL request will fail.
  • If no port is configured. In the case of myServer.com, the requested URL cannot contain the port, even the default port 443. A request to myserver.com:443 will fail.
  • Domain name must be registered by ICP;
  • For safety reasons,api.weixin.qq.comCannot be configured as a server domain name, and the associated API cannot be called within the applets.Developers should save AppSecret to a backend server and use it through the servergetAccessTokenInterface to getaccess_tokenAnd call the relevant API;
  • You can configure a maximum of 20 domain names for each interface.

2. Network request

timeout

  • The default timeout duration and maximum timeout duration are 60s.
  • The timeout period can be inapp.jsongame.jsonThrough thenetworktimeoutConfiguration.

Use restrictions

  • Network-requestedrefererHeader cannot be set. Its format is fixed ashttps://servicewechat.com/{appid}/{version}/page-frame.html, including{appid}Is the appID of the applet,{version}Is the version number of the small program0Represents the development version, trial version, and review version, and the version number isdevtoolsRepresents as developer tools, and other official versions;
  • Wx. request, wx.uploadFile, and wx.downloadFile have a maximum of 10 concurrent requests.
  • The maximum concurrency limit for wx.connectsockt is 5.
  • Small program into the background after running, if5sThe internal network request is not completed and an error message will be called backfail interrupted; The network request interface call will not be called until it comes back to the foreground.

Return value encoding

  • It is recommended that the server return value be utF-8 encoded. For non-UTF-8 encodings, the applet will try to convert, but the conversion may fail.
  • The applet automatically filters the BOM (only one BOM).

The callback function

  • As long as the server successfully receives the return, regardlessstatusCodeWhatever it is, it goes insuccessThe callback. Please judge the return value according to the business logic.

3. Frequently Asked Questions

The HTTPS certificate

Applets must use HTTPS/WSS to initiate network requests. During the request, the system verifies the HTTPS certificate used by the server domain name. If the verification fails, the request cannot be initiated. Due to system limitations, different platforms have different degree of strict requirements for certificates. To ensure the compatibility of small programs, you are advised to configure certificates according to the highest standards and use related tools to check whether the existing certificates meet requirements. The requirements for certificates are as follows:

Certificate validity can be verified using the openssl s_client-connect example.com:443 command, or by using other online tools.

In addition to the network request API, if other HTTPS requests in the applets are abnormal, follow the preceding procedure to check them. For example, HTTPS images cannot be loaded, and audio and video cannot be played.

6. My stomping record

Record some problems that took me a long time, and also attach my time of stepping pits, hoping to help those in need. Where is the small program pit? Select the third-party framework MPvue and van, then pay attention to the problem of writing. Developer tools need to be updated to the latest version, and the expected effect does not appear during compilation. It may need to clear the cache of developer tools, or rm -rf dist, run NPM run dev command to recompile. Follow the prompts to the wechat development community, or other search engines to search the problem, one by one, do not panic.

UsingComponents importing van components globally has no effect

** 2020-03-02: ** Mpvue constructs the project, in app.json, global importvanThe component doesn’t work. It has nothing to do with the awesome component, because the developer tools on my computer were installed a long time ago, andusingComponentsThank you for solving my problem with this article.link



Iphone8Plus Preview mode Van component page appears blank

**2020-03-13: ** debug environment: iPhone8plus, developer tool V1.02.1911180, in the developer tool preview, real machine debugging can be normal display, but the real machine scan preview mode of the QR code, can only see the bottom tabbar, content area is blank, as shown in the figure:

Solution:

  • Using components, unable to preview? link

undefined is not an object(evaluating ‘document.getElementsByTagName’)

Solution:link

Because there is no document small program, I introduced the ali cloud icon, there is a document. The getElementsByTagName code,

This problem occurs when you get to the demo version. /static/iconfont/ iconfont +demo.html…. Caused by these unrelated documents; The iconfont folder is as follows

Delete irrelevant files

sudo rm -rf dist
npm run dev
Copy the code

Delete the entire dist file = “recompiling =” clear the cache in the developer tools = > click compile = “click preview =” sweep phone code = “correctly solved the problem, my mobile phone preview hang problem is solved, when the development of the program must console error is solved, then to locate some strange questions.

An error occurs when the developer tool is started after the computer restarts



** Solution: ** Close VPN or packet capture tool = “close developer tool =” “restart developer tool =” clear all cache = “click preview =” OK

Since the wechat developer tool uses Https connections, any applications that may affect the network should be closed.

Otherwise, it may have an impact on developer tools.

does not have a method “onClickLeft” to handle event “click-left”.

Redirect pages cannot be defined in app.json. For example, you must not define the solution in tabbar’s path: github.com/youzan/vant…

wx.nextTick is not a function

Solution: BecauseSet the base library, has not updated the base library, change the base library to the latest 2.10.2, it can work normally.



The DATA cannot be obtained when request BEGIN appears in an HTTPS network request on iOS







Objects in a two-dimensional array share a memory address

As a result, when filling in the reimbursement details form, the value of two-way data binding will affect the value of other details forms, resulting in submission failure. The problem is solved by dynamically creating memory addresses that do not point to an address.

let parmas = [];
// let obj = {}; Get rid of this line of code
      console.log(this.formsDetails, "====> this.formsDetails");
      for (let i = 0; i < this.formsDetails.length; i++) {
        let detail = this.formsDetails[i];
        let index = i;
        // params.push(obj) removes this line of code
        // Create objects dynamically instead of sharing a memory space
        parmas.push({});
        parmas[i]["sno"] = ++index;
        parmas[i]["expenseuid"] = this.mainObj.expenseuid;
        for (let j = 0; j < detail.length; j++) { parmas[i][detail[j].field] = detail[j].value; }}console.log(JSON.stringify(parmas, null.2), "insertPmemExpenseDetail=====>datas");
    
Copy the code

Mpvue nested component data cannot be updated in real time

Solution 1: Combine the two components into one

The simplest and most crude way is to merge the two components into one, and update the data within one component, so that there is no data synchronization between the components. The problem with this, however, is that the current component is large, and we split the component in the first place for decoupling, so we can’t go back to the past.

Solution 2:watch

In the ununit. vue component, watch is used to listen for changes in an attribute, so that when external data changes, watch can listen:

watch: { 'user.age': function(val, oldVal){ this.render(); // When the age property in user changes, call the render method}}Copy the code

Solution 3: Use VUEX state management data

Multidimensional array changes length view not updated

Solution:

this.businesstypes = [...this.businesstypes];
Copy the code

7. Build and release process

7.1. Upload code

The premise of uploading the code in the wechat developer tool is that when the project is imported, the binding to the AppID (non-test AppID) is consistent with the developer background to appID, and the submission record can only be seen in the background after the code is uploaded

7.2 Developer background submission for review

After upload code review submission, audit time, generally within 7 working days, as it is now also want to experience the online version, then we can set up an online version, in the background and setting experience members (members is not set to experience the qr code and code is unable to open small programs), so developers, testing of internal members can experience online version in advance.

8. User experience

8.1. Do not customize nav-bar

  • Is not the custom

Wechat has its own nav-bar, which also supports returning to the previous page. I did not choose to customize nav-bar, but chose wechat’s own navigation bar and dynamically set title. ** My starting point: ** small program, the more lightweight the better, not the pursuit of flashy, is the function of ease of use, fluency, convenience, namely go.

8.2. The submit button is fixed at the bottom

** My starting point: ** Users can operate the submit button in the process of filling out the form without scrolling again. The button is obvious and easy to use.

8.2. The login button is disabled

If the user name or password is empty, disable the button instead of prompting the user that the user name or password cannot be empty

The resources

conclusion

Record this article, more importantly, to record a problem solving process, do a good small program there are many better solutions, I also need to slowly explore. In fact, I also face difficulties in the selection of technology, in the end is the choice of wechat small program native development flexibility is stronger? Or do you choose a small framework (such as MPvue, Taro, etc.) to develop quickly? Is cross-end supported? And so on these problems have bothered me, but then I think, brave to do, encounter problems to solve, after summary, step on the pit more will have experience, in order to better help their own technology selection, the less experience will be more tangled.