Uni-app has become so popular recently that major recruitment requirements add uni-app to their job requirements. Therefore, I used uni-app to develop a wechat official account project of my company at my own risk.

This article is for those with experience in Vue development.

First, preparation

Download the HBuilderX editor

Download the HBuilderX editor. HBuilderX is the official uni-App recommendation, which includes visual construction of uni-App projects, running projects, packaging and compiling projects.

The download address is here, because I only develop the wechat public account project, which is also the H5 project, so only the standard version can be downloaded.

2. Solve the problem that HBuilderX editor cannot format less files

I am using less as the precompiled language for CSS. If you choose sass as the precompiled language for CSS, you can skip this step.

Modify the configuration of these two files to solve this problem.

Add the contents in the red box.

2. Create uni-APP project

Creating a project in the HBuilderX editor is easy in just two steps.

It is recommended to choose the built-in UNI-UI project template, which has a large number of common components built in and does not remove too many useless files and code.

After creation, the directory structure of the project is shown in figure 1

  • Components places built-in components.
  • Pages places the development page.
  • Static Static resources.
  • App.vue project page main entrance is equivalent to vue project app. vue.
  • Main.js is equivalent to Vue project main.js.
  • Manifest.json packages some compile-related configurations.
  • Pages. Json configures routing, window styles, native navigation bar, and bottom native tabbar.
  • Uni.scss configures common style variables built into uni-app.

3. Launch uni-APP project

Launching the Uni-app project in the HBuilderX editor is also very easy in one step.

Begin to compile

Compile successfully

Open http://loaclhost:8080/ in the browser. If the following figure is displayed, the project is successfully started.

Iv. Development stage

How to remove the native navigation bar

I don’t have a native navigation bar in my prototype, so I’m going to remove it.

The method is in this document right here.

Native navigation is not displayed when navigationStyle is custom or titleNView is false. So there are two ways to get rid of the native navigation bar on the H5 end.

It’s all in the pages. Json file

Unified removal of native navigation bar

"pages": [ { "path": "pages/index/index", "style": { "navigationStyle": "custom", "navigationBarTitleText": "Uni-ui Foundation Project"}}],Copy the code

Alternatively, remove the native navigation bar for the H5 end only.

"pages": [
    {
        "path": "pages/index/index",
        "style": {
            "h5":{
                "titleNView":false
            }
        }
    }
],
Copy the code

Here’s what it looks like without the native navigation bar

2. Route configuration

At present, most front-end projects use routing to control page jumps, so when entering a new framework, we should first attribute how to configure the routing of this framework.

Uni-app routes are configured in much the same way as applets, which is much easier if you know how to applets.

The route of the uni-app project is configured in the Pages property of pages. Json, which has already been applied.

The value of the Pages property is an array, and each item in the array is a JSON object. Each route is configured in the JSON object, where the path property is the page path and the style is configured for the page.

In the uni-app project, we usually write pages in the Pages folder, for example, in the Pagse folder we add a file called home.vue, which reads as follows

<template> <view> </template> <script> </script> </style> </style>Copy the code

So we’re going to do this in pages. Json.

"pages": [
    {
        "path": "pages/index/index",
        "style": {
            "navigationStyle": "custom"
        }
    },
    {
        "path": "pages/home",
        "style": {
            "navigationStyle": "custom"
        }
    }
],
Copy the code

Refresh the page and you will find that there is no I’m Home page in your browser.

Of course, this is not a configuration error. However, uni-App has a stipulation that the first entry of the Pages node is the application entry page. So we’re going to change that.

"pages": [
    {
        "path": "pages/home",
        "style": {
            "navigationStyle": "custom"
        }
    },
    {
        "path": "pages/index/index",
        "style": {
            "navigationStyle": "custom"
        }
    },
],
Copy the code

And then you see that the compilation failed.The reason is that in uni-app configuration files,The tail can’t be added to each term.(comma)., remove the comma, refresh the page after compiling, and you’ll seehome.vueThe contents of this page.

Now let’s delete the home.vue file. When compiling, we will get an error.

We can’t find the home.vue file, so we need to modify the Pages array whenever we add/subtract pages.

"pages": [
    {
        "path": "pages/index/index",
        "style": {
            "navigationStyle": "custom"
        }
    },
],
Copy the code

Recompiling succeeded.

3. How to introduce the Ali icon

Ali ICONS are used in almost every project.

In the Vue project, we introduced the Ali icon in the index.html file in the public folder, via link.

But there is no index.html file in the Uni-app project, so where to introduce it.

As mentioned earlier, app. vue is the main entrance of the project page, so we can try to introduce it here.

In the Vue project. In the Vue file we introduce styles like this

<style lang="less" scoped>
    @import "./css/index.less";
</style>
Copy the code

Go to MDN to check @import usage (entry) and find @import can be used in this way.

@import url("chrome://communicator/skin/");
Copy the code

So try introducing the Ali icon in app. vue like this

<style>
    @import url("https://at.alicdn.com/t/font_1811528_5xzkmbymkb7.css");
</style>
Copy the code

Then use this in the pages/index/index.vue file

<template>
    <view class="container">
        <text class="iconfont iconSIMCard"></text>
    </view>
</template>
Copy the code

Refresh the page and find that the import is successful.

4, about the use of labels

If you are small program development, this point can be ignored.

We used H5 to develop the wechat public account. Naturally, we can use THE HTML5 label. Such as div, SPAN, img.

is equivalent to

,< text> is equivalent to , is equivalent to .

5. The problem of picture path

Speaking of this path, we need to make some common sense first.

~ represents the Web application root, / also represents the root,.. / indicates the upper level of the current directory, and./ indicates the current directory.

To import images in uni-App project, the built-in component tag is used, whose SRC attribute is to configure the image path. Only relative path and absolute path are supported, and base64 code is supported. However, when is used in custom components, If SRC uses a relative path, path search may fail. Therefore, you are advised to use an absolute path.

In my project I put the image resources in the assets/images folder in the root directory. If your page has a deep path in the Pages folder, for example

Is that what you’re gonna write on the page

<template> <view> <image src=".. /.. /.. /.. /assets/images/indeximg1.png"></image> </view> </template>Copy the code

In fact, we can use ~ to transform.

<template>
    <view>
        <image src="~assets/images/indeximg1.png"></image>
    </view>
</template>
Copy the code

Using background in less can also use ~

.home{
    background:url(~images/card/home.png) no-repeat;
}
Copy the code

Writing in this way can be avoided because less or more.. / causes path errors, which can be easily configured.

In addition, we can add a vue.config.js file in the root directory of the Vue project to configure webpack. Of course, there are differences between the configuration in uni-app project and Vue project.

We configure a path alias in the vue.config.js file as we did in the Vue project.

const path = require('path');
function resolve(dir) {
    return path.resolve(__dirname, dir)
}
module.exports = {
    configureWebpack: config => {
        return baseConfig = {
            resolve: {
                extensions: ['.js', '.vue', '.json'],
                alias: {
                    'assets': resolve('assets'),
                    'css': resolve('assets/css'),
                    'images': resolve('assets/images'),
                }
            },
        }
    },
}
Copy the code

6. Use of third-party components

Third party components used in uni-app are downloaded to the Components folder. So introducing third-party components is the same as Vue project development.

If you want to use a Popup layer, introduce it like this

components: {
    uniPopup: () => import('@/components/uni-popup/uni-popup.vue'),
    uniPopupDialog: () => import('@/components/uni-popup/uni-popup-dialog.vue'),
},
Copy the code

7, about the page jump

  • Page and transfer

NavigateTo () : uni. NavigateTo () : uni. NavigateTo () : uni. NavigateTo () : uni. NavigateTo () : uni.

uni.navigateTo({ url: 'test? id=1&name=uniapp' });Copy the code
Export default {onLoad: function (option) {// Option is object, which serializes console.log(option.id); // Prints out the arguments passed from the previous page. console.log(option.name); // Prints out the arguments passed from the previous page. }}Copy the code
  • The page stack

The framework manages all current pages in the form of a stack, remembering that the stack is first in and last out.

NavigateBack triggers uni. NavigateBack when the user presses the back button in the upper left corner and the Android user clicks the physical back button. NavigateBack closes the current page and returns to the previous page. The OBJECT. Delta in uni. NavigateBack controls which level of the page stack to return to. You can use getCurrentPages() to get objects for all page stacks.

Uni.navigateto (), keep the current page, push the current page, then jump to a new page.

Uni.redirectto () : closes the current page, does not push the current page, and jumps to a new page.

Uni.navigateto (), uni.redirectto () can only open non-tabbar pages.

You can’t jump to pages in app. vue. If you refresh the entire page with the browser, the current page stack is cleared.

8, about the use of message popovers

When interacting with the server, you must use message pop-ups, such as an error message. The UNI-App framework encapsulates the footprint of several message pop-ups.

Uni.showtoast () displays a message prompt pop-up window. Uni.hidetoast () Hides the message prompt box. Uni.showmodal () displays modal pop-ups, similar to standard HTML message boxes: Alert and confirm.

10. The use of loading animations

Uni.showloading () Displays the loading prompt box. You need to call uni.hideloading () to close the loading prompt box.

Uni.hideloading () Hides the loading prompt.

ShowToast and showLoading are the same underlying layer, so showToast and showLoading will overwrite each other, and uni.hideloading () will also turn showToast off, so pay attention to the call order.

An Invalid Host header error occurred with the nginx reverse proxy

Json file and set “disableHostCheck”: true in the devServer option in H5.

12, About using the formData format request interface

Uni-app uses uni.request() to communicate with the server. The data parameter is the data passed to the server.

The final data sent to the server is of type String. If the data passed in is not of type String, it is converted to String. The conversion rules are as follows:

  • For the GET method, the data is converted to a Query String. For example {name: ‘name’, age: 18} the converted result is name=name&age=18.
  • Json serialization is performed for data with the POST method and header[‘content-type’] as application/ JSON.
  • For data whose POST method and header[‘content-type’] is Application/X-www-form-urlencoded, the data will be converted to a Query String.

Uni.request () cannot send formData to the back end. To send data of type formData, use uni.uploadfile (), which uploads the local resource to the developer server. The client issues a POST request, where content-type is multipart/form-data.

The formData parameter is used to upload additional form data from the local resource to uni.uploadfile ().

Uni.uploadfile () requires url, filePath and name. So uni.uploadfile () can be used to initiate an interface request with data format formData.

13. Get the element size

Because uni-App does not support the introduction of DOM manipulation plug-ins such as jQuery, H5 platform can be used through conditional compilation. Instead of using jQuery in uni-App, use uni.createsElectorQuery () to create an instance of SelectorQuery to retrieve DOM information.

For example, to get
height.

const _this = this;
uni.createSelectorQuery().select(".p-list").boundingClientRect(data => {
    _this.height = data.height;
}).exec();
Copy the code

14. Realization of the region pull-up refresh function

The scroll-View built-in component of UNI-App and the third-party uni-load-more component are used to achieve this.

Note that the scroll view will take effect only if it is set to a fixed height.

<template> <view class="p-list"> <scroll-view scroll-y="true" @scrolltolower="lower" :style="{height:height+'px'}"> <view v-for="item in list">{{item}}</view> <uni-load-more :status="status" iconType="auto" v-show="isShow"></uni-load-more> </scroll-view> </view> </template> <script> export default { data(){ return { IsShow :false, status: 'loading',// Load more states}}, components: {uniLoadMore: {uniLoadMore: () => import('@/components/uni-load-more/uni-load-more.vue'), }, mounted() { this.getViewHeight(); }, methods: { getViewHeight() { const _this = this; uni.createSelectorQuery().select(".p-list").boundingClientRect(data => { _this.height = data.height; }).exec(); }, lower() { if (this.isShow) return; this.isShow = true; this.current++; this.getList(); }, getList(){ let data = new Object; data.current = this.current; data.size = 15; Api.getrenewrecord (data). Then (res => {this.isShow = false; if (res.code == 200) { this.list = [...this.list, ...res.data] if (res.data.length == 0) { this.status = 'noMore'; this.isShow = true; } } }) .catch(err => { this.isShow = false; }) } } } </script>Copy the code

15. Implementation of the region drop-down refresh function

If the page header has fixed content, the drop-down refresh can only be implemented using the built-in scrollView component. Note that the scroll view will take effect only if it is set to a fixed height.

<template> <view class="p-list"> <scroll-view scroll-y refresher-enabled :refresher-triggered="triggered" :refresher-threshold="100" @refresherrefresh="onRefresh" :style="{height:height+'px'}"> <view v-for="item in List ">{{item}}</view> </scroll-view> </view> </template> <script> export default {data(){return {current:1,// page number }}, mounted() {this.getViewheight (); // This.getViewheight () {this.getViewheight (); }, methods: { getViewHeight() { const _this = this; uni.createSelectorQuery().select(".p-list").boundingClientRect(data => { _this.height = data.height; }).exec(); }, onRefresh() { if (this.triggered) return; this.triggered = true; this.current++; this.getList(); }, getList(){ let data = new Object; data.current = this.current; data.size = 15; // API. GetRenewRecord (data). Then (res => {this. Triggered = false; if (res.code == 200) { this.list = [...res.data,...this.list] } }) .catch(err => { this.triggered = false; }) } } } </script>Copy the code

Because in wechat browser, the whole page will slide when it is pulled down, which will cause the scroll view refresh to be stuck. Solve it in the following ways

Start by enabling the pull-down refresh listener for the page in pages. Json

{
   "pages":[
    	{
            "path": "testList",
            "style": {
                "enablePullDownRefresh": true
            }
        },
    ]
}
Copy the code

Then listen for the pull-down refresh on the page and execute uni. StopPullDownRefresh to disable the pull-down refresh immediately.

onPullDownRefresh() {
     uni.stopPullDownRefresh()
},
Copy the code

Meanwhile, in app. vue, hide the effect of the pull-down refresh page

<style>
    uni-page[data-page=websms] uni-page-refresh {
        display: none;
    }
</style>
Copy the code

16, IOS fold up the soft keyboard after the page does not slide solution

<template> <view> <input v-model.trim="value" @blur="handleblur"/> </view> </template> <script> export default{ methods:  { handleblur() { uni.pageScrollTo({ scrollTop: 0, duration: 0 }); }, } } </script>Copy the code

17, IOS6 can’t open display:flex nested use of parent height

Add the min-height attribute to the parent element. Or avoid nesting

18, About customizing the wrapped index.html page

Uni-app projects have no index.html by default, unlike Vue projects that have index.html by default. How to use CND to import third-party libraries.

First, create an index. HTML file in the root directory

<! DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, Minimum - scale = 1.0 "> < title > < % = htmlWebpackPlugin. Options. The title % > < / title > < script > document.addEventListener('DOMContentLoaded', function() { document.documentElement.style.fontSize = document.documentElement.clientWidth / 20 + 'px' }) </script> <link rel="stylesheet" href="<%= BASE_URL %>static/index.<%= VUE_APP_INDEX_CSS_HASH %>.css" /> </head> <body> <noscript>  <strong>Please enable JavaScript to continue.</strong> </noscript> <div id="app"></div> <! -- built files will be auto injected --> </body> </html>Copy the code

Then add the following configuration to manifest.json.

"h5":{
    "template": "index.html",
}
Copy the code

19. Operation on the optimization of the first screen

Enable tree shaking and preloading and add the following configuration to manifest.json.

"h5":{
    "optimization": {
        "prefetch": true,
        "preload": true,
        "treeShaking": {
            "enable": true
        }
    }
}
Copy the code

20. About the slow loading of the IOS first screen.

You can see here

5. Deployment phase

1. Release of H5

First configuration

And then package and compile

Finally, the generated files are packaged and deployed to the server.