uniapp learning notes

Posted by Distant_storm on Sun, 26 Dec 2021 23:21:29 +0100

frame

life cycle

Application lifecycle

Main life cycle
  • onLaunch

Triggered when the uni app initialization is completed (only triggered once globally)

  • onShow

When the uni app starts, or enters the foreground display from the background

  • onHide

When the uni app enters the background from the foreground

  • onError

Triggered when the uni app reports an error

  • onUnhandledRejection

Listener function for unhandled Promise reject event (2.8.1 +)

  • onPageNotFound

There is no listening function on the page. After the page is opened (such as directly opening a page by sharing a card or applet code), it will be triggered if it is found that the page does not exist. The api jump to a page that does not exist will not be triggered (such as uni.navigateTo)

matters needing attention
  • The app lifecycle is available only in app Listen in Vue. Listening in other pages is invalid.

Page lifecycle

Main life cycle
  • onLoad

Listen for page loading. Its parameters are the data passed from the previous page. The parameter type is Object (used for page parameter passing). Refer to Example

// In test Vue page accepts parameters
export default {
    onLoad: function (option) { //option is of object type, which will serialize the parameters passed on the previous page
        console.log(option.id); //Print out the parameters passed on the previous page.
        console.log(option.name); //Print out the parameters passed on the previous page.
    }
}
  • onShow

    The listening page is displayed. The page is triggered every time it appears on the screen, including returning from the lower page point to expose the current page.

  • onReady

    The first rendering of the listening page is completed. Note that if the rendering speed is fast, it will be triggered before the page enters the animation.

  • onHide

    Listening page hidden

  • onUnload

    Listening page unloading

  • onPullDownRefresh

    Listen to user pull-down actions, which are generally used for pull-down refresh.

  • onReachBottom

    The event that scrolls the page to the bottom, which is often used to drop down the data of the next page.

    If the page does not scroll due to the use of scroll view, the bottom touch event will not be triggered.

  • onTabItemTap

    Triggered when tab is clicked. The parameter is Object.

    attribute type explain
    index String The sequence number of the clicked tabItem, starting from 0
    pagePath String Page path of the clicked tabItem
    text String The button text of the clicked tabItem

    onTabItemTap is often used to click the current tabitem to scroll or refresh the current page. If you click a different tabitem, it will trigger page switching.

    onTabItemTap : function(e) {
        console.log(e);
        // The return format of e is json object: {"index":0,"text": "home page", "pagePath":"pages/index/index"}
    }

     

  • onShareAppMessage

    Users click the upper right corner to share

  • onPageScroll

    Listen for page scrolling. The parameter is Object

    attribute type explain
    scrollTop Number The distance the page has scrolled in the vertical direction (in px)
    • Don't write complex interactive js, such as frequently modifying pages. Because this life cycle is triggered in the rendering layer, js is executed in the logic layer at the non h5 end, and the communication between the two layers is lossy. If the data exchange between the two layers is triggered frequently in the rolling process, it may cause jamming.

    • stiky ceiling example

    • wxs can also be used to monitor scrolling in App, wechat applet and H5

  • onShareTimeline

    Listening users click the upper right corner to forward to the circle of friends

  • onAddToFavorites

    Listen to the user and click favorites in the upper right corner

Vue lifecycle

activated,deactivated

Applet not supported

 

global variable

Common module

This method is convenient to maintain, but the disadvantage is that it needs to be introduced every time.

  1. Create a common directory under the root directory of the uni app project, and then create a new global. Com directory under the common directory JS is used to define common methods and properties.

// common/global.js
const websiteUrl = 'http://uniapp.dcloud.io';  
const now = Date.now || function () {  
    return new Date().getTime();  
};  
const isArray = Array.isArray || function (obj) {  
    return obj instanceof Array;  
};  
​
export default {  
    websiteUrl,  
    now,  
    isArray  
}
  1. Next, in pages / index / index The module is referenced in Vue

<script>  
    import helper from '@/common/global.js';  
​
    export default {  
        onLoad(){  
            console.log('now:' + helper.now());  
        }
    }  
</script>

Mount globalProperties

Extend some frequently used constants or methods directly to global properties. Just in main JS can be called directly in each page.

// main.js
app.config.globalProperties.$websiteUrl='http://www.baidu.com'
​
// index.vue
console.log(this.$websiteUrl)

 

matters needing attention

  • Do not duplicate property or method names in each page.

  • This method only supports vue pages.

globalData

App. Related configurations of global data defined in Vue

export default {  
    globalData: {  
        text: 'text'  
    }
}  

index. This value can be obtained and modified in Vue

console.log(getApp().globalData.text)
getApp().globalData.text = 'test'
console.log(getApp().globalData.text)

matters needing attention

When onLaunch is applied, the getApp object has not been obtained. You can use this globalData get globalData.

 

Cross end development

Please change the element selector of body to page. Similarly, div, ul and li to view, span and font to text, a to navigator and img to image

There are native components on the non-H5 side, which raises the concept that the level of native components is higher than that of front-end components. To block native components such as video and map, please use the cover view component.

url(//alicdn.net) and other paths, change to URL( https://alicdn.net ), because / / on the App side is the file protocol

grammar

Vue2

Basics

v-once

h5. Wechat applets are not supported

v-html

The App side and H5 side support v-html, the wechat applet will be converted to rich text, and other ends do not support v-html.

class and style

Support attribute object, string array and calculation of attribute string

Binding Class and Style on custom components is not supported.

conditional rendering

v-show does not support template elements or v-else

List rendering

Use v-for to traverse the property of an object.

<template>
    <view>
    <view v-for="(value, name) in object">
        {{ name }}: {{ value }}
    </view>
    </view>
</template>
<script>
    export default {
        data() {
            return {
                object: {
                    title: 'How to do lists in Vue',
                    author: 'Jane Doe',
                    publishedAt: '2020-04-10'
                }
            }
        }
    }
</script>
  • There are differences between the H5 platform and other platforms when using v-for circular integers. For example, in v-for="(item, index) in 10", the H5 platform starts with 1 and the other platforms start with 0. The second parameter index can be used to maintain consistency.

  • The applet side data is updated by difference. Because the applet does not support deleting object properties and uses the method of setting the value to be null instead, it may not meet the expectations during traversal. You need to filter the data with null value by yourself( relevance feedback).

Event handler
Event modifier
  • . stop: supported by all platforms, it will prevent event bubbling when used, and it will also prevent the default behavior of events at the non-H5 end

  • . Native: listen for native events, which are supported by all platforms

Event mapping table
{
    click: 'tap'
}

assembly

Applet support

Uni app only supports vue single file components (. vue components).

Dynamic components are not supported

Custom render is not supported

< script type = "text / x-template" > string templates are not supported

Asynchronous slots are not supported

Keep alive is not supported

transition is not supported

grammar

ref

The non H5 end can only be used to obtain custom components, not built-in component instances (such as view and text)

is

This property is not supported because dynamic components are not supported

Built in components

component

Applet not supported

transition,transition-group

app, applet does not support

keep-alive

app, applet does not support

 

API

Global API

nextTick

Wechat applet does not support, but the VM inside the instance$ Nexttick() is supported.

directive

Wechat applet does not support

filter

Wechat applet does not support

Instance properties

vm.$el

app, applet does not support

vm.$attrs,vm.$listeners

Applet not supported

Template instruction

v-html

Wechat applet will be converted to rich text

v-pre

The contents in this node will not be compiled and can display native double parentheses, which is not supported by applets

v-cloak

When used with CSS rules such as [v-cloak] {display: none}, uncompiled tags will not be displayed until compilation is completed.

app, applet does not support

v-once

Applet not supported

Vuex

modules

getters, variations and actions in modules will not be divided into modules. Methods with the same name shall be subject to the first defined method

// moduleA.js
export default{
	state:{
		text:'A text'
	},
	getters:{
		timeNow(state){
			return state.text
		}
	}
}
//moduleB.js
export default{
	state:{
		text:'B text',
		timestamp:new Date()
	},
	getters:{
		timeNow(state){
			return state.timestamp
		}
	}
}

// store/index.js
modules:{moduleA,moduleB}

//index.vue
data() {
    return {
        text:this.$store.getters.timeNow // Return A text
    }
}

Vue3

transfer

life cycle

In Vue3, the lifecycle of component unloading is renamed

  • Changed destroyed to unmounted

  • Change beforeDestroy to beforeUnmount

event

emits

Vue3 now provides an emits option, similar to the existing props option. This option allows you to define the events that a component can emit to its parent object

<template>
  <div>
    <p>{{ text }}</p>
    <button v-on:click="$emit('accepted')">OK</button>
  </div>
</template>
<script>
  export default {
    props: ['text'],
    emits: ['accepted']
  }
</script>
Modifier

Removed native modifier

v-model

Vue3 v-model prop and event default names changed props Value is changed to props modelValue ,event. Value is modified to update:modelValue

filters

Since Vue 3.0, filters have been deleted and are no longer supported. It is recommended to replace them with method calls or calculated properties.

event processing

Multi event processor

There can be multiple methods in an event handler separated by comma operators:

<template>
	<view>
    <!-- these two items. one() and two() The button click event will be executed -->
    <button @click="one($event), two($event)">
        Submit
    </button>
    </view>
</template>
<script>
    export default {
        methods: {
            one(event) {
                // first handler logic...
                console.log("event1: ",event);
            },
            two(event) {
                // second handler logic...
                console.log("event2: ",event);
            }
        }
    }
</script>

assembly

Prop case naming

attribute names in HTML are case insensitive, so browsers interpret all uppercase characters as lowercase characters. This means that when you use the template in DOM, the prop name of camelCase (hump naming method) needs to be named with its equivalent kebab case (DASH delimited naming)

inheritance of attribute

If you do not want the root element of the component to inherit attribute, you can set inheritattributes: false in the options of the component. For example:

<template>
<view class="date-picker">
    <input type="datetime" v-bind="$attrs" />
    </view>
</template>
<script>
    export default {
        inheritAttrs: false
    }
</script>

With this new configuration, the data status attribute will be applied to the input element!

<!-- Date-picker Components using non prop attribute -->
    <date-picker data-status="activated"></date-picker>

<!-- Render date-picker assembly -->
    <view class="date-picker">
        <input type="datetime" data-status="activated" />
	</view>

Custom event

It is recommended to always use the event name of kebab case.

It is recommended that you define all emitted events to better document how the component should work.

export default {
    //1. Declare custom event: the custom event of a component must be declared in the emits node in advance
    emits:['count-change'],
    ...
}
    
// Validate custom events
// To add validation, the event is assigned a function that receives the parameters passed to the $emit call and returns a Boolean value indicating whether the event is valid.
export default {
    emits: {
        // No validation
        click: null,

        // Validate submit event
        submit: ({ email, password }) => {
            if (email && password) {
                return true
            } else {
                console.warn('Invalid submit event payload!')
                return false
            }
        }
	},
    methods: {
        submitForm() {
            this.$emit('submit', { email, password })
        }
    }
}

v-model

By default, v-models on components use modelValue as prop and update:modelValue as events. We can modify these names by passing parameters to v-model:

<my-component v-model:foo="bar"></my-component>

You can now create multiple v-model bindings on a single component instance

In this example, the subcomponent will need a foo prop and issue an update:foo event to synchronize:

<template>
    <view>
        <input type="text" :value="foo" @input="$emit('update:foo', $event.target.value)" >
    </view>
</template>
<script>
    export default {
        props: {
            foo: String
        }
    }
</script>
Handling v-model modifiers

Provided to components through modelModifiers prop

// Parent component
<my-component v-model.capitalize="myText"></my-component>
// Subcomponents
<input type="text" :value="modelValue" @input="emitValue" style="border: red solid 1px;">
<script>
    export default {
        props: {
            modelValue: String,
            modelModifiers: {
                default: () => ({})
            }
        },
        methods: {
            emitValue(e) {
                let value = e.target.value
                if (this.modelModifiers.capitalize) {
                    value = value.charAt(0).toUpperCase() + value.slice(1) // Processing modifier
                }
                this.$emit('update:modelValue', value)
            }
        }
    }
</script>

For v-model bindings with parameters, the generated prop name will be arg + "Modifiers":

// Parent component
<my-component v-model:foo.capitalize="bar"></my-component>
// Subcomponents
<input type="text" :value="foo" @input="$emit('update:foo', $event.target.value)">

API

Example method

  • $forceUpdate

    Force component instances to re render. Note that it only affects the instance itself and the subcomponents inserted into the slot content, not all subcomponents.

WXS

wxs is the script language of wechat applet in the view layer, which can achieve better front-end interaction and optimize performance.

More dom operations for the view layer.

The trigger method is the same as that of js. The @ symbol is used to trigger, and the logic is written in the view layer. Specify the prefix to be used when calling through module, and lang specifies that the script type is wxs.

Wechat canvas cannot be operated through wxs

<template>
	<view>
		<view class="area">
			<view @touchstart="test.touchstart" @touchmove="test.touchmove" class="movable">{{test.msg}}</view>
		</view>
	</view>
</template>
<script module="test" lang="wxs">
	var startX = 0
	var startY = 0
	var lastLeft = 50;
	var lastTop = 50

	function touchstart(event, ins) {
		console.log("touchstart")
		var touch = event.touches[0] || event.changedTouches[0]
		startX = touch.pageX
		startY = touch.pageY
	}

	function touchmove(event, ins) {
		var touch = event.touches[0] || event.changedTouches[0]
		var pageX = touch.pageX
		var pageY = touch.pageY
		var left = pageX - startX + lastLeft
		var top = pageY - startY + lastTop
		startX = pageX
		startY = pageY
		lastLeft = left
		lastTop = top
		ins.selectComponent('.movable').setStyle({
			left: left + 'px',
			top: top + 'px'
		})
		return false
	}
	module.exports = {
		msg: 'Hello',
		touchstart: touchstart,
		touchmove: touchmove
	}
</script>

Style and layout

Style import

Use the @ import statement to import the external style sheet, @ import followed by the relative path of the external style sheet to be imported, with; Indicates the end of the statement.

Example code:

<style>
    @import "../../common/uni.css";

    .uni-card {
        box-shadow: none;
    }
</style>
  • Only class selectors are supported in wechat applet custom components

  • Defined in app The style in Vue is a global style, which acts on every page.

  • The style defined in the vue file in the pages directory is a local style, which only works on the corresponding page and will overwrite the app The same selector in vue.

  • It is recommended to use the absolute path starting with ~ @ for the reference path of the local background picture.

Built in CSS variables

CSS variables describe App Applet H5
--status-bar-height System status bar height System status bar height . nvue note: see below 25px 0
--window-top The distance from the content area to the top 0 0 The height of the NavigationBar
--window-bottom The distance from the content area to the bottom 0 0 Height of TabBar

For the four small programs of wechat / QQ / Baidu / byte beating, the custom components will have one more node than the App/H5 end when rendering, so you need to pay attention when writing styles

to configure

manifest.json

networkTimeout

Configure the timeout of request, socket, file upload and download, in milliseconds

{
	"name": "Demo",
	"appid": "",
	"networkTimeout": 6000
}

 

pages.json

globalStyle

  • onReachBottomDistance

    The distance from the bottom of the page when the pull-up bottom event is triggered. The unit only supports px, and the default is 50

easycom

As long as the components are installed in the components directory of the project and comply with components / component name / component name vue directory structure. You can use it directly in the page without reference and registration.

assembly

Form component

picker

The select tag of H5 is replaced by the picker component

radio-group

The form element radio is replaced by a radio group component

Applet customization component

  1. Copy the custom component to the corresponding directory

┌─wxcomponents                  Wechat applet custom component storage directory
│   └──custom                   Wechat applet customization component
│        ├─index.js
│        ├─index.wxml
│        ├─index.json
│        └─index.wxss
  1. Introduction component

In pages Add the components to be imported into the page configuration corresponding to JSON

{
    "path": "pages/slide-view/slide-view",
    "style": {
        "navigationBarTitleText": "slide-view",
        "usingComponents": {
            "slide-view": "/wxcomponents/slideview/index"
        }
    }
}

 

  1. Using custom components

The name of the custom component must be consistent with the name defined in usingComponents

<slide-view width="750" height="110" slide-width="500">
    <view slot="left" class="l">
        <image src="/static/file_transfer.jpg" class="img"></image>
        <view class='text'>
            <view class='title'>File transfer assistant</view>
            <view class='time'>7:00 PM</view>
        </view>
    </view>
    <view slot="right" class="r">
        <view class='read'>Mark as read</view>
        <view class='delete'>delete</view>
    </view>
</slide-view>
  1. Compile run

During compilation, the corresponding vue files will be generated in the custom component directory

  1. matters needing attention

  • When you need to use applet components in vue components, pay attention to pages usingComponents is configured in the global style of JSON instead of page level configuration.

 

Frame interface

Page communication

  • App global level, across any component, page, nvue, vue, etc

  • When using, pay attention to destroy event monitoring in time

uni.$once(eventName,callback)

Listen for global custom events. Events can be generated by uni$ Emit triggers, but only once. Remove the listener after the first trigger.

parameter type describe
eventName String Event name
callback Function Callback function for event
uni.$once('update',function(data){
    console.log('Listening to events from update ,Carry parameters msg Is:' + data.msg);
})

uni.$on(eventName,callback)

Listen for global custom events. Events can be generated by uni$ Emit trigger.

parameter type describe
eventName String Event name
callback Function Callback function for event
uni.$on('update',function(data){
    console.log('Listening to events from update ,Carry parameters msg Is:' + data.msg);
})

uni.$emit(eventName,OBJECT)

Trigger a global custom event.

parameter type describe
eventName String Event name
OBJECT Object Additional parameters carried by the trigger event
uni.$emit('update',{msg:'Page update'})

uni.$off(eventName, callback)

Remove the global custom event listener.

parameter type describe
eventName Array<String> Event name
callback Function Callback function for event
Tips
  • If no parameters are provided, remove all event listeners;

  • If only an event is provided, remove all listeners of the event;

  • If both event and callback are provided, only the listener of this callback will be removed;

  • The provided callback must be the same as the callback of $on to remove the listener of this callback;

API

Network request

request

The applet cannot keep cookie s. You can use tools to solve this problem:

A line of code lets WeChat, headlines, Baidu, Alipay applet support cookie, compatible with uni-app

Requests can be intercepted using third-party interceptors:

luch-request

Upload file

Wechat applet only supports single file upload

You can refer to the customer service feedback in Hello uni app to support multi image upload

Download File

The temporary path of the file can be used normally during the startup of the application. If you need to save it permanently, you need to actively call Uni Savefile can be accessed the next time the application starts.

WebSocket

Wechat applet platform 1.7 0 and above, up to 5 WebSocket connections can exist at the same time.

media

Picture preview

On the non-H5 side, previewImage is implemented natively, and the flexibility of interface customization is low.

The plug-in market has previewImage implemented by the front-end, whose performance is lower than that of the native implementation, but the interface can be defined at will

Select a picture or video

Some mobile phones do not support the specified front camera. You need to open the shooting interface to switch by yourself

The number of files that can be selected by ios real machine of wechat applet cannot be greater than 9

Select a file (not a picture or video)

Wechat applet does not support selecting files

You can use Wx Choosemessagefile (object), select a file from the wechat chat session.

audio frequency

uni.createInnerAudioContext() can play audio

If you need to play audio at double speed, you can replace it with video at double speed. There are encapsulated plug-ins in the plug-in market Audio speed doubling

Background audio

Still playing after exiting the applet

Because the background audio playback consumes the power of the mobile phone, the platform has control, and the application needs to be filled in the manifest.

Applet platform, which needs to be in manifest JSON, fill in "requiredBackgroundModes": ["audio"]. The platform will audit when the applet is published

Camera assembly

uni.createCameraContext

It implements a non full screen camera

Wechat applet realizes the requirements of OCR and other certificate identification, and the plug-in market also has encapsulation and search ocr so

Camera access required

file

uni.saveFile

saveFile will move the temporary file, so the tempFilePath passed in after the call is successful will not be available.

uni.openDocument

Open file in wechat

Data cache

  • Each applet has its own storage api, and the data storage life cycle is consistent with the applet itself, that is, the data is always available unless the user actively deletes it or is automatically cleaned up after a certain time.

  • Emptying Storage on non App platforms will result in uni The deviceId obtained by getsysteminfo has changed

position

uni.getLocation

Applet: api does not return detailed address Chinese description by default. have access to Gaode map API obtain

In wechat applet, when the user leaves the application, this interface cannot be called and needs to be applied Background continuous positioning permission In addition, it needs to be used in the new version wx.onLocationChange Monitor the change of location information; When the user clicks "display at the top of chat", this interface can continue to be called.

The < Map > component defaults to the coordinates of the National Survey Bureau and calls Uni When the returned result of getlocation is passed to the < Map > component, the type must be specified as gcj02.

uni.openLocation

Open map view location

Routing and page Jump

Cannot be in app Page Jump in Vue.

uni.navigateTo

Keep the current page, jump to a page in the application, and use Uni Navigateback can return to the original page.

Parameter description

  1. url

    Path + parameter path? key=value&key2=value2

    //Jump to test. On the start page Vue page and pass parameters
    uni.navigateTo({
        url: 'test?id=1&name=uniapp'
    });

    The url has a length limit. If the string is too long, the delivery will fail

    When special characters such as spaces appear in the parameter, the parameter needs to be encoded

<navigator :url="'/pages/test/test?item='+ encodeURIComponent(JSON.stringify(item))"></navigator>

<script>
// In test Vue page accepts parameters
onLoad: function (option) {
    const item = JSON.parse(decodeURIComponent(option.item));
}
</script>
  1. events

    The inter page communication interface is used to listen to the data sent by the open page to the current page.

// 2.8. 9 + support
uni.navigateTo({
  events: {
    // Add a listener for the specified event to get the data transferred from the open page to the current page
    acceptDataFromOpenedPage: function(data) {
      console.log(data)
    },
    someEvent: function(data) {
      console.log(data)
    }
  }
})

// uni.navigateTo target page pages / test vue
onLoad: function(option) {
  const eventChannel = this.getOpenerEventChannel();
  eventChannel.emit('acceptDataFromOpenedPage', {data: 'test'});
  eventChannel.emit('someEvent', {data: 'test'});
}
  1. success

    Interface calls the callback function successfully

success: function(res) {
    // Transfer data to the opened page through eventChannel
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test' })
}

// uni.navigateTo target page pages / test vue
onLoad: function(option) {
  const eventChannel = this.getOpenerEventChannel();
  // Listen to the acceptDataFromOpenerPage event to obtain the data transmitted from the previous page to the current page through the eventChannel
  eventChannel.on('acceptDataFromOpenerPage', function(data) {
    console.log(data)
  })
}
  1. fail

    Interface call failed callback function

  2. complete

    Callback function at the end of interface call (both successful and failed calls will be executed)

matters needing attention

  • Only non tabBar pages can be opened.

  • The target page of the routing API must be in pages vue page registered in JSON

  • If you want to open the web url, you can use plus.com on the App platform runtime. OpenURL or web view component; H5 platform uses window open; The applet platform uses the web view component (the url needs to be in the applet's online white list).

uni.redirectTo

matters needing attention

  • Only non tabBar pages can be opened.

uni.switchTab

matters needing attention

  • Only tabBar pages can be opened.

uni.reLaunch

matters needing attention

  • You can open any page.

uni.navigateBack

matters needing attention

  • After the H5 side page is refreshed, the page stack will disappear. At this time, the navigateBack cannot be returned. If it is necessary to return, you can use history Back() navigate to the browser's other history.

EventChannel

Inter page event communication channel

EventChannel.on(string eventName, function fn)

Continuously listening for an event

  • string eventName event name

  • function fn event listener function

EventChannel.once(string eventName, function fn)

Listen to an event once, and it will become invalid after triggering

  • string eventName event name

  • function fn event listener function

EventChannel.emit(string eventName, any args)

Trigger an event

  • string eventName event name

  • any args event parameter

EventChannel.off(string eventName, function fn)

Cancel listening for an event. When the second parameter is given, only the given listening functions are cancelled, otherwise all listening functions are cancelled.

  • string eventName event name

  • function fn event listener function

 

Interface

Pull down refresh

onPullDownRefresh

Need to be in pages JSON, find the pages node of the current page and turn on enablePullDownRefresh in the style option.

{
    "pages": [
        {
            "path": "pages/index/index",
            "style": {
                "navigationBarTitleText": "uni-app",
                "enablePullDownRefresh": true
            }
        }
    ]
}

At the same level as lifecycle functions such as onLoad

export default {
    onPullDownRefresh() {
        console.log('refresh');
    }
}

uni.startPullDownRefresh(OBJECT)

Start the pull-down refresh, and trigger the pull-down refresh animation after calling. The effect is consistent with the user's manual pull-down refresh.

You can use Uni Setbackgroundtextstyle dynamically sets the drop-down background font and the style of loading diagram.

OBJECT parameter description

Parameter name type Required explain
success Function no Interface call successful callback
fail Function no Interface call failed callback function
complete Function no Callback function at the end of interface call (both successful and failed calls will be executed)

success return parameter description

parameter type explain
errMsg String Interface call result
uni.startPullDownRefresh({
    success: (errMsg) => {
        console.log(errMsg) // {"errMsg":"startPullDownRefresh:ok"}
    },
    fail:(errMsg) => {
        console.log(errMsg)
    },
    complete:(errMsg) => {
        console.log(errMsg) // {"errMsg":"startPullDownRefresh:ok"}
    }
});

uni.stopPullDownRefresh()

After processing the data refresh, uni Stoppulldownrefresh can stop the pull-down refresh of the current page.

onPullDownRefresh() {
    console.log('refresh');
    setTimeout(function () {
        uni.stopPullDownRefresh();
    }, 1000);
}

Navigation bar

When the bottom page of the applet opened by the user is not a home page, the default "home page" button is displayed by default. The developer can call hideHomeButton in page onShow to hide it.

TabBar

If you want a tabbar with a + sign in the middle, create a new uni app project in HBuilderX and select the bottom tab template

Face recognition

Uni app wechat applet access to face core SDK

performance optimization

Applet side

For complex pages, when updating the data of an area, it is necessary to make the area into a component, so that when updating the data, only this component will be updated, otherwise the data of the whole page will be updated, resulting in click delay.

uniCloud

cloud storage

uni-file-picker File selection upload

 

 

doubt

Routing and page Jump

  • The tabBar at the bottom of the page is determined by the page, that is, as long as it is a page defined as a tabBar, there is a tabBar at the bottom.

  • Page routing interception and management. There are many encapsulated tools in the plug-in market, such as search route

Topics: app