UniAPP Quick start learning

I. Introduction to UniAPP

(1) What is UniAPP?

Uni-app is a framework for developing all front-end applications using vue. js. Developers write a set of code, which can be published to iOS, Android, H5 and various small programs (wechat/Alipay/Baidu/Toutiao/QQ/Dingding) and other platforms. It is convenient for developers to deliver quickly without changing their development thinking. No change in development habits is required.

(2) Why do YOU choose UniAPP?

  1. More developers/cases

Hundreds of thousands of applications, UNI statistics monthly live 1.2 billion, 70+ wechat/QQ groups

  1. Platform capabilities are not limited

At the same time, through conditional compilation + platform-specific API calls, you can elegantly write personalized code for one platform and invoke proprietary capabilities without affecting other platforms

  1. Excellent performance experience

The App side supports native rendering to support smoother user experience. The performance of the small program side is better than other frameworks in the market

  1. Rich surrounding ecology

There are thousands of plug-ins in the plug-in market, supporting NPM, supporting small program components and SDK. Various SDK of wechat ecology can be directly used for cross-platform APP

  1. Low learning cost

Based on the common front-end technology stack, using VUE syntax + wechat small program API, no extra learning costs

(3) UniAPP functional framework

(4) Establishment of UniAPP development environment

  1. Download the development tool HBuilderX

HBuilderX is a generic front-end development tool with special enhancements for UNI-App.

Download App development version, available out of the box; If you download the standard version, you will be prompted to install the UNI-App plug-in when running or distributing uni-App. You can use the plug-in after downloading it

  1. Create the Uni-app project

Select uni-app type, enter project name, select template, and click Create.

Uni-app comes with the template Hello Uni-App, which is the official component and API example.

Another important template is the UNI UI project template, which is recommended for daily development and has a number of common components built in.

  1. Run the uni – app

Mainly include: browser running, real machine running, small program running

  1. Uni – app

Mainly include: cloud native APP, offline native APP, H5, various small programs

Ii. UniAPP initialization configuration

(1) Project directory structure

Chrysene - Components UNI - ├ ─ garbage -a.vuereusableaComponent ├ ─ hybrid is to store the local web directory (build) ├ ─ platforms for each platform dedicated page directory (build) ├ ─ pages business page file storage directory │ ├ ─ index │ │ └ ─ index.vue├ ─ ├ ─list.vue├─ Static For storing application references to static resources (like pictures, videos, etc.) Static resources can only be stored here ├─ WXComponents ├─ Common Resources ├─ API Request ├─ Store State Management ├─main.jsVue Initializes the entry file ├─App.vueApplication configuration, used to configure App global style and monitor application life cycle ├─manifest.json├ ─pages configure the app name, appID, LOGO, and version.jsonConfigure page information such as routing, navigation bar, and tabsCopy the code

prompt

  • staticJs files in the directory below will not be compiled by Webpack. If there is ES6 code inside, it will be run directly without conversion, and an error will be reported on mobile devices.
  • soLess, SCSSAnd other resources are also not placedstatic Directory, it is recommended that these public resources be placed commondirectory

(2) Apply manifest.json

The manifest.json file is the application configuration file that specifies the application name, icon, permissions, etc. It is also where we can set up the cross-domain interception handler for Vue for H5

(3) Compile and configure vue.config.js

Vue.config.js is an optional configuration file that is automatically loaded if it exists in the root directory of the project and is typically used to configure compilation options such as webpack. The official documentation

(4) Global configuration page. Json

The pages. Json file is used to configure uni-app globally, determining the path of the page file, window style, native navigation bar, native tabbar at the bottom, etc. It is similar to the page management section of app.json in wechat applets.

The official documentation

attribute type mandatory describe
globalStyle Object no Sets the window appearance of the default page
pages Object Array is Set the page path and window presentation
easycom Object no Components automatically import rules
tabBar Object no Sets the performance of the bottom TAB
condition Object no Boot Mode Configuration
subPackages Object Array no Subcontract loading configuration
preloadRule Object no Subcontract pre-download rules

(5) Global style UNI.scSS

The uni.scSS file is used to facilitate overall control of the style of the application. For example, button color, border style, uni. SCSS file has a batch of SCSS variable presets. The official documentation

Uni-app extensions (UNI UI) and many third party plug-ins on the market use these style variables. If you are a plugin developer, you are advised to use SCSS preprocessing and use these variables directly in the plugin code (without importing this file). It is convenient for users to develop an App with a consistent overall style by building blocks.

Uni.scss is a special file that can be used in SCSS code without importing this file. The uni-app compiler specifically handles this uni.scss in the Webpack configuration so that each SCSS file is injected into the uni.scss to make it globally available. If you want global use of less, stylus, you need to configure the Webpack policy in vue.config.js.

(6) Main component app.vue

App.vue is the main component of Uni-app. All pages are switched under app. vue, which is the page entry file. But app.vue itself is not a page, and you can’t write view elements here.

The purpose of this file is to call application lifecycle functions, configure global styles, and configure global storage globalData

The application lifecycle can only be listened on app.vue, not on the page.

(7) Entry file main.js

Main.js is the entry file for uni-app. It is mainly used to initialize vue instances, define global components, and use necessary plug-ins such as vuex.

The official documentation

(8) UniAPP development specification and resource path

  1. Development specification conventions
  • Page File Wizard Vue Single file Component (SFC) specification
  • Component labels are close to the applets specification, see the UNI-APP Component specification
  • Interconnection capability (JS API) is close to wechat applets specification, but it needs to replace WX with UNI. See UNI-APP interface specification for details
  • Data binding and event handling are the same as the vue.js specification and complement the App and page life cycles
  • It is recommended that you develop with a Flex layout for multiterminal compatibility
  1. Resource Path Description

Template to date static resources such as image, video, etc. SRC attributes, you can use relative path or absolute path, the form is as follows:

<! -- absolute path, /static: static directory in root directory, in cli project /static: static directory in SRC directory -->
<image class="logo" src="/static/logo.png"></image>
<image class="logo" src="@/static/logo.png"></image>
<! -- Relative path -->
<image class="logo" src=".. /.. /static/logo.png"></image>
Copy the code

Pay attention to

  • The @ initial absolute and relative paths are verified by base64 conversion rules
  • Static resources for appointments are not converted to Base64 on non-H5 platforms
  • H5 platform, resources less than 4KB will be converted to Base64, the rest will not be transferred

Js file or script tag, you can use relative path and absolute path, the form is as follows:

// Absolute path, @ points to the project root directory, in cli projects @ points to the SRC directory
import add from '@/common/add.js'
// Relative path
import add from '.. /.. /common/add.js'
Copy the code

You can use relative and absolute paths in the CSS file or style tag as follows:

/* Absolute path */
@import url('/common/uni.css');
@import url('@/common/uni.css');
/* Relative path */
@import url('.. /.. /common/uni.css');
Copy the code

The path of the image referenced in the CSS file or the style tag can be relative or absolute. The format is as follows:

/* Absolute path */
background-image: url(/static/logo.png);
background-image: url(@/static/logo.png);
/* Relative path */
background-image: url(. /.. /static/logo.png);
Copy the code

Iii. UniAPP life cycle

What is the core purpose of learning a tool? Is to solve the core business logic problems, business logic often simply explain a sentence: “do the right thing at the right time”, OK! What is the right time? In simple terms, page running process, the stages of the callback function is a time of the page, and we also call this as “hooks” life cycle, of course, in business we also wrote a lot of “correction” logic, the callback is also our custom timing, UniAPP life cycle of the hook function callback function is what? Let’s understand!

Uni-app fully supports the Vue instance life cycle, as well as the application life cycle and page life cycle.

(1) Application life cycle

The function name instructions
onLaunch whenuni-appTriggered when initialization is complete (globally only fired once)
onShow whenuni-appStart, or enter foreground display from background
onHide whenuni-appGo from the front to the back
onError whenuni-appTriggered when an error is reported
onUniNViewMessage rightnvuePage to send data to monitor, refer toNvue communicates with VUE
onUnhandledRejection Reject an unprocessed Promise event listener function (2.8.1+)
onPageNotFound There are no listener functions on the page
onThemeChange Listen for system topic changes

(2) Page life cycle

The function name instructions
onLoad Listen to the page load, its parameter is the data passed last page, parameter type is Object (used for page parameter), refer toThe sample
onShow Listen to the page display. Fires every time the page appears on the screen, including returning from sub-page points to reveal the current page
onReady The listener page is rendered for the first time. Note that if the rendering is fast, it will trigger before the page is animated
onHide Listening page hiding
onUnload Listening page uninstallation
onResize Listen for window size changes
onPullDownRefresh Monitor user pull down, generally used for pull down refresh, referenceThe sample
onReachBottom An event to scroll to the bottom of a page (not to the bottom of a scroll view), usually used to pull down data from the next page. See notes below for details
onTabItemTap When TAB is clicked, the parameter is Object. For details, see notes below
onShareAppMessage Users click on the upper right to share
onPageScroll Listen for page scrolling with Object
onNavigationBarButtonTap Listen for the native title bar button click event with the Object parameter
onBackPress Listening page return
onNavigationBarSearchInputChanged Listen for changes in the native title bar search input box
onNavigationBarSearchInputConfirmed Listen for the native title bar search input box search event, triggered when the user clicks the “search” button on the soft keyboard.
onNavigationBarSearchInputClicked Listen for native title bar search input box click events
onShareTimeline Listen to the user click on the upper right corner to forward to moments
onAddToFavorites Listen to the user click favorites in the upper right corner

4. UniAPP routing configuration and page skipping

(1) Route configuration

Uni-app page routing is all managed by the framework. Developers need to configure the path and page style of each routing page in pages. Json (similar to the configuration of page routing in app.json by applet).

"pages": [{"path": "pages/index"."style": {
				"navigationBarTitleText": "Route Configuration"."navigationBarBackgroundColor": "#FFFFFF"."navigationBarTextStyle": "black"."backgroundColor": "#FFFFFF"."enablePullDownRefresh": true}}, {"path": "pages/user"."style": {
				"navigationBarTitleText": "Route Configuration"."navigationBarBackgroundColor": "#FFFFFF"."navigationBarTextStyle": "black"."backgroundColor": "#FFFFFF"."enablePullDownRefresh": true}}]Copy the code

(2) Route jump

Uni-app has two types of page routing jump: navigator component jump (tabular navigation) and API jump (programmatic navigation)

The framework manages all the current pages in the form of a stack. When route switching occurs, the page stack behaves as follows:

routing Page stack representation trigger
Initialize the New page is pushed The first page uni-app opens
Open a new page New page is pushed Call APIuni.navigateTo,

Using the component<navigator open-type="navigate" />
Page redirection The current page is out of the stack, and the new page is in the stack Call APIuni.redirectTo 、

Using the component
The page returns The page goes off the stack until the target returns to the page Call APIuni.navigateBack 、

Using components,

Users press the back button in the upper left corner and Android users press the physical Back button
The Tab to switch All pages are off the stack, leaving only new Tab pages Call APIuni.switchTab 、

Using components,

User switch Tab
Heavy load All pages are off the stack, leaving only new pages Call APIuni.reLaunch 、

Using the component

(3) Get the current page stack

The getCurrentPages() function is used to get an instance of the current page stack, as an array in stack order, with the first element being the home page and the last element being the current page.

Note: getCurrentPages() is only used to display the page stack. Do not modify the page stack to avoid page status errors.

(4) Participating in receiving routing

The onLoad() function of the page lifecycle listens for the page load and takes the data passed from the previous page, for example:

// Page jumps and passes parameters
uni.navigateTo({
    url: 'page2? name=liy&message=Hello'
});
Copy the code

Url indicates the path of the page to be jumped, and parameters can be set after the path. Between parameters and paths? Parameter keys and parameter values are connected by =, and different parameters are separated by &. Such as’ path? Key1 =value2&key2=value2′, where path is the path to the next page, and the onLoad function on the next page gets the parameters to pass.

// Page 2 receives parameters
onLoad: function (option) { // Option is of type object, which serializes the arguments passed on the previous page
	console.log(option.name); // Prints out the arguments passed from the previous page.
	console.log(option.message); // Prints out the arguments passed from the previous page.
}
Copy the code

Note: URL has length limit, too long string will fail to transfer, and non-standard character format may also lead to failure to transfer, so it is recommended to use encodeURI, decodeURI for complex parameters after processing transfer

(5) Small program routing and subcontracting configuration

Due to the limitation of size and resource loading of applets, various applets platforms provide subcontracting methods to optimize the download and startup speed of applets.

The main package is where the default startup page and TabBar page are placed, and the subpackages are divided according to the configuration of pages.json.

When the small program starts, the main package will be downloaded and the page in the main package will be started by default. When the user enters a page in the subpackage, the corresponding subpackage will be automatically downloaded and displayed after downloading. At this time, there will be a waiting prompt in the terminal interface.

"subPackages": [{"root": "news"."pages": [{
					"path": "index"."style": {
						"navigationBarTitleText": "Press center"."navigationBarBackgroundColor": "#FFFFFF"."navigationBarTextStyle": "black"."backgroundColor": "#FFFFFF"}}]}... ] .// Preload subcontracting Settings
"preloadRule": {
		"pages/index": {
			"network": "all"."packages": ["activities"]}}Copy the code

5. Introduction to common components of UniAPP

Uni-app provides a set of basic components for developers, similar to the basic tag elements found in HTML, but uni-App’s components are different from HTML, similar to applets, and more suitable for mobile applications.

It is not recommended to use HTML tags, but in fact, if developers write div tags, the compiler will convert them to view tags when compiling to non-H5 platforms, as well as span to text, A to Navigator, etc., including CSS element selectors. However, for the convenience of management and policy unification, it is still recommended to use components such as View when writing new code.

Developers can combine these base components for rapid development. Based on the built-in base components, they can develop various extension components with the same specification as vUE components.

Case: Bosom sister layout implementation

6. Brief introduction of common API of UniAPP

The JS code of uni-App, h5 terminal runs in the browser, non-H5 terminal Android platform runs in v8 engine, iOS platform runs in the JScore engine of iOS. So the jsAPI of UNI-App consists of the STANDARD ECMAScript JS API and the UNI extension API.

ECMAScript is managed by Ecma International and is the basic JS syntax. Browser based on the standard JS extension window, Document AND other JS API; Node.js expands fs modules based on standard JS; Applets also extend various Wx.xx, my.xx, swan.xx apis based on standard JS.

There are many standard ECMAScript apis, such as console, setTimeout and so on.

Non-h5, although it does not support the JS API of window, Document, Navigator and other browsers, it does support standard ECMAScript.

Developers should not equate browser JS to standard JS.

So the non-H5 side of UNI-App also supports standard JS, if and for syntax, strings, arrays, time and other variables and various processing methods, but does not support browser-specific objects.

Case study: Bosom sister chat function

Vii. UniAPP custom components and communication

(1) Custom component concept

Component is a very important part of VUE technology. Component makes it easy to manufacture and share uI-related wheels, which greatly improves the development efficiency of VUE users. Store components in the component directory of the project.

Components can be used using global registration and page import in three steps:

Import import XXX from ‘XXX’

Vue. Use (‘xx’,xx) Components :{XXX}

Using the < / a > xx

(2) Parent-child component communication

  1. The parent component passes data to the child component through custom properties

  2. The child component receives data passed by the parent component through props

  1. The parent component passes events to child components through custom event tags
  2. The child modifies the parent component data by triggering the parent component definition event

(3) Slot Data distribution and scope slot

  1. The parent component works by calling the child component’s internal nested HTML contentslotDistribute to child components
  2. The child component passes through theslotAdd attributes to the tag, communicate data to the parent component, scope slot

(4) Global event definition and communication

  1. It can be used anywhere throughout the applicationuni.$onCreate a global event
  2. It can also be used anywhere throughout the applicationuni.$emitTo trigger global events to achieve multi-component data communication

UniAPP Vuex state management

  1. concept

Vuex is a state management mode developed specifically for vue.js applications. It uses centralized storage to manage the state of all components of an application and rules to ensure that the state changes in a predictable way.

  1. Application scenarios

Data or state needs to be shared between Vue components.

  1. The key rules
  • State: Stores status data
  • Getter: Derived data from State data, equivalent to the computed property of State
  • Mutation: Stores the method used to synchronize changed state data. The default parameter passed in is state
  • Action: Stores state data for asynchronous changes, not directly, but by triggering the Mutation method, with the default parameter context
  • Module: Vuex modularity
  1. Interaction between

  1. use
import {
		mapState,
		mapActions
} from 'vuex'
export default {
		computed: {
			...mapState(['loginState'.'userInfo'])},methods: {
			...mapActions(['userLoginAction'.'userLogoutAction']),}}Copy the code
  1. Experience case: simulation user login logic implementation

Note: Use Storage together to achieve the business requirement of maintaining the state after refreshing the page

Nine, operating environment judgment and cross-terminal compatibility

(1) Development environment and production environment

Uni-app uses process.env.node_env to determine whether the current environment is a development environment or a production environment. It is generally used to connect to test servers or production servers for dynamic switching.

In HBuilderX, clicking “run” to compile code is the development environment, and clicking “publish” to compile code is the production environment

if(process.env.NODE_ENV === 'development') {console.log('Development Environment')}else{
    console.log('Production environment')}Copy the code

(2) Judge the platform

Platform judgment has two scenarios, one is at compile time and the other is at run time.

Compile-time judgment Compile-time judgment, that is, conditional compilation, different platforms after compiling packages are different code,

// #ifdef H5
 alert("Only H5 platform has alert method")
// #endif
// The above code will only be compiled into the H5 distribution, other packages will not include the above code.
Copy the code

Run-time check Run-time check indicates that you still need to check the platform during runtime after the code has been sent to the package. In this case, use uni.getSystemInfosync (). Platform to check whether the client environment is Android, iOS or a small program development tool

switch(uni.getSystemInfoSync().platform){
   case 'android':
      console.log('Running on Android')
      break;
   case 'ios':
      console.log('Running on iOS')
      break;
   default:
      console.log('Running on developer tools')
      break;
}
Copy the code

(3) Cross-end compatibility

Uni-app has encapsulated common components and JS apis into the framework. Developers can develop according to uni-App specifications to ensure the compatibility of multiple platforms. Most services can be directly satisfied.

  • Writing a lot of if else can lead to poor code performance and confusing management.
  • Compiling to a different project and then modifying it twice can make subsequent upgrades very troublesome.

C uses #ifdef, #ifndef to compile different code for Windows, MAC, and other oss. Uni-app takes this idea into consideration and provides uni-App with a conditional compilation method, which gracefully implements platform personalization in a single project.

Conditional compilation is marked with special comments that are used to compile code for different platforms at compile time.

** Begins with #ifdef or #ifndef plus %PLATFORM% and ends with #endif.

  • \#ifdef: if defined exists only on a platform
  • \#ifndef: if not defined Exists except for a platform
  • %PLATFORM% : indicates the PLATFORM name

%PLATFORM% can be:

value platform
APP-PLUS App
APP-PLUS-NVUE App nvue
H5 H5
MP-WEIXIN Wechat applets
MP-ALIPAY Alipay small program
MP-BAIDU Baidu applet
MP-TOUTIAO Bytedance applet
MP-QQ QQ small programs
MP-360 360 small programs
MP Wechat small program/Alipay small program/Baidu small program/bytedance small program /QQ small program /360 small program
QUICKAPP-WEBVIEW Quick Application General (including Alliance and Huawei)
QUICKAPP-WEBVIEW-UNION Fast Application Alliance
QUICKAPP-WEBVIEW-HUAWEI Quick Application Huawei