directory

  • Uni-app project construction
  • routing
  • Request tool encapsulation
  • How are UI components introduced

Uni-app project construction

What is the uni – app

Uni-app is a framework for developing all front-end applications using vue.js. Developers write a set of code that can be published to iOS, Android, Web (responsive), mini programs (wechat/Alipay/Baidu/Toutiao /QQ/ Dingding/Taobao), Kuaiapp and many other platforms.

Why uni-app

Uni-app has a stronger advantage in 8 key metrics: number of developers, cases, cross-end flatness, scalability flexibility, performance experience, surrounding ecology, learning cost, and development cost.

How to create a project with UNI-app

Use HBuilderX to create a project modeled after the UNI-UI project

Note:

1. After successfully creating the project, download some compilation plug-ins (built-in terminal, SCSS compilation, UNI-APP compilation, built-in browser, etc.)

2. If the plug-in fails to be downloaded or installed, you can directly decompress the plug-in package to the plugins under the installation directory of HBuilderX. If the HBuilder installation fails, you can find the installation directory ->update->plugins installation package directly decompress to the installation directory ->plugins

Plug-ins or dependent tools required by the business project can be found in thePlug-in marketImport into the project

  • If it is the first time to run the small program, you need to set the installation path of the small program IDE and set the AppId of the small program, as shown in the following figure

Use vuE-CLI to install the project

<! --> vue create -p dcloudio/uni-preset-vue my-project <! --> NPM run dev:%PLATFORM%<! --> NPM run build:%PLATFORM%
Copy the code

PLATFORM reference value

value platform
app-plus App platform generates packaged resources (NPM Run Build: app-Plus is supported for continuous integration. Run is not supported, run debugging still needs to be done in HBuilderX)
h5 H5
mp-alipay Alipay small program
mp-baidu Baidu applet
mp-weixin Wechat applets
mp-toutiao Bytedance applet
mp-qq Qq small programs
mp-360 360 small programs
quickapp-webview Fast application (webview)
quickapp-webview-union Fast Application Alliance
quickapp-webview-huawei Quick Application Huawei

The development of specification

  • Page files follow the Vue Single file Component (SFC) specification
  • Component labels are close to the applets specification, see uni-App Component specification Uni-App Component specification
  • Interface capability (JS API) is close to wechat applets specification, but the prefix wx should be replaced with UNI, see UNI-APP Interface specification
  • Data binding and event handling are the same as the vue.js specification and complement the App and page lifecycle
  • It is recommended that you develop with a Flex layout for multiterminal compatibility

The directory structure

Chrysene ─uniCloud cloud space directory, Ali cloud uniCloud - aliyun, tencent cloud uniCloud - TCB (see uniCloud) │ ─ components conform to the vue component specifications of uni - app directory components │ └ ─ comp - Dr. Ue reusable components a ├ ─ hybrid App end to store local HTML file directory, see ├─ Platforms to store each dedicated page directory, │ ├─index │ ├─ ├─ list │ ├─ ├─ vue list │ ├─ vue list │ ├─ vue list │ ├─ vue Note: Static resources can only be stored in this ├─uni_modules plugin for [uni_module](/uni_modules). │ ├─ WxComponents │ ├─ app.vue │ ├─ wxComponents │ ├─main.js │ Vue ├─ H5.template. HTML HTML Template ├─manifest.json To configure application name, AppID, logo, version, etc. ├ ─pages.json configure page routes, navigation bars, tabs, etcCopy the code

Tips

  • When compiled to any platform, files in the static directory are packaged completely and not compiled. Files in non-static directories (vue, JS, CSS, etc.) are packaged and compiled only when referenced.
  • Static js files will not be compiled. If es6 code is in the static directory, an error will be reported on the mobile device.
  • Do not store the CSS and less/ SCSS resources in the static directory. You are advised to store these public resources in the self-created common directory.
  • HbuilderX 1.9.0+ supports the creation of ext.json, sitemap.json files in the root directory.

routing

In my previous uniApp project there were two ways to handle page routing jumps

  • The official apis of UNI-App are used to redirect routes, and then a secondary encapsulation is performed for these apis to simulate route interception
  • Uni -simple-router is used for route management

Simulate the encapsulation of route hopsOfficial jump document

const navigateTo = (params) = > {
	let token = uni.getStorageSync("token");
	// Other operations
	if(token){
		// You can check the token again
		uni.navigateTo(params)
	}else{
		uni.redirectTo("login=?"+params.url)
	}
}

const redirectTo = (params) = > {
	let token = uni.getStorageSync("token");
	// Other operations
	if(token){
		// You can check the token again
		uni.redirectTo(params)
	}else{
		uni.redirectTo("login=?"+params.url)
	}
}

const reLaunch = (params) = > {
	let token = uni.getStorageSync("token");
	// Other operations
	if(token){
		// You can check the token again
		uni.reLaunch(params)
	}else{
		uni.redirectTo("login=?"+params.url)
	}
}


const switchTab = (params) = > {
	let token = uni.getStorageSync("token");
	// Other operations
	if(token){
		// You can check the token again
		uni.switchTab(params)
	}else{
		uni.redirectTo("login=?"+params.url)
	}
}

const navigateBack = (params) = > {
	let token = uni.getStorageSync("token");
	// Other operations
	if(token){
		// You can check the token again
		uni.navigateBack(params)
	}else{
		uni.redirectTo("login=?"+params.url)
	}
}


const preloadPage = (params) = > {
	let token = uni.getStorageSync("token");
	// Other operations
	if(token){
		// You can check the token again
		uni.preloadPage(params)
	}else{
		uni.redirectTo("login=?"+params.url)
	}
}

module.exports = {
	navigateTo,
	redirectTo,
	reLaunch,
	switchTab,
	preloadPage
}
Copy the code

Of course, for easy use, the above encapsulation can be mounted to the vue instance in main.js or directly mixed into the app.vue component using mixins

uni-simple-router

A more concise VuE-Router, specifically designed for Uni-app

introduce

Uni-simple – Router is a router specially designed for UNI-APP. Its deep integration with the Uni-App core makes it a breeze to build single-page applications with uni-App. Features include:

  • The H5 terminal can be completely developed using vue-Router.

  • Modular, component-based router configuration.

  • Routing parameters, queries, wildcards.

  • H5 view the transition effect powered by the uni-simple-Router transition system.

  • More granular navigation control.

  • H side automatically controls active CSS class links.

  • Wildcard applet end, APP end, H5 end.

Install the uni – simple – the router
  1. The plugin market is imported directly using HBuilder

Because the official documentation of uni-simple-Router recommends using NPM installation, importing HBuilder needs to be done by yourself. So I looked for similar cases on the Internet and found a feasible solution as follows! Zip package link :uni-simple-router

  • Directory as follows

  • By unpacking the package into the specified directory, I created a directory for the Js_SDK

  • Create a router directory, where the route declaration and route interception are the same as vue-router.

  • router/index.js

import modules from './modules'
import Vue from 'vue'
import Router from '@/js_sdk/uni-simple-router/index.js'

Vue.use(Router)
/ / initialization
const router = new Router({
	encodeURI:true.routes: [...modules]/ / the routing table
});

const whiteList = ['/pages/login/login'] 
// Global route front-guard
router.beforeEach((to, from, next) = > {
	let token='token';
	if(token){
		 next()
	}else{
		if(whiteList.indexOf(to.path) ! = = -1) {
		  next()
		}else{
		  next({ path: '/pages/login/login'}}}})// Global route post guard
router.afterEach((to, from) = > {
	console.log("afterEach")})export default router;
Copy the code
  • main.js
import Vue from 'vue'
import App from './App'
import router from './common/router'
import {RouterMount} from './js_sdk/uni-simple-router/index.js'

Vue.config.productionTip = false

App.mpType = 'app'

const app = newVue({ ... App })// #ifdef H5
	RouterMount(app,'#app');
// #endif

// #ifndef H5
	app.$mount(); // In order to be compatible with small programs and app side must be written this way to have effect
// #endif

Copy the code
  1. Router is used in the same way as VUE
npm install uni-simple-router --save
Copy the code

Pay attention to

The router page path must be the same as the pages path in pages. Json

Commonly used API
  1. Router instance method
router.beforeEach((to, from, next) = > {
  // 'to' and 'from' are both routing objects
})

router.afterEach((to, from) = > {
  // 'to' and 'from' are both routing objects
})
router.push({name:'tab1'})
router.replace({name:'tab1'})
router.replaceAll({name:'tab1'})
router.pushTab({name:'tab1'})
router.back(2, {success:(. arg) = >{
        console.log(arg)
    }
})
Copy the code
  1. Uni-app official route jump method ‘link’
NavigateBack: uni. NavigateBack: uni. NavigateBack: uni.
/ / 2.8.9 + support
uni.navigateTo({
  url: 'pages/test? id=1'.events: {
    // Adds a listener to the specified event to get data from the opened page to the current page
    acceptDataFromOpenedPage: function(data) {
      console.log(data)
    },
    someEvent: function(data) {
      console.log(data)
    }
    ...
  },
  success: function(res) {
    // Send data to the opened page via eventChannel
    res.eventChannel.emit('acceptDataFromOpenerPage', { data: 'test'})}})// Close the current page and go to a page in the application.
uni.redirectTo({
    url: 'test? id=1'
});

// Close all pages to open a page within the app
uni.reLaunch({
    url: 'test? id=1'
});

// Jump to the tabBar page and close all other non-Tabbar pages
uni.switchTab({
    url: '/pages/index/index'
});

// Close the current page and return to the previous page or multi-level page. GetCurrentPages () gets the current page stack and determines how many layers you need to return.
// Note: When the navigateTo jump is called, the page that called the method is added to the stack, whereas the redirectTo method is not. See the sample code below

// Here is the page A
uni.navigateTo({
    url: 'B? id=1'
});

// This is page B
uni.navigateTo({
    url: 'C? id=1'
});

// navigateBack in C will return to A
uni.navigateBack({
    delta: 2
});

// Preloading pages is a performance optimization technique. Preloaded pages open faster.
uni.preloadPage({url: "/pages/test/test"});
Copy the code

Request tool encapsulation

In the Vue project we used axios as the front-end HTTP request tool, so uni-App also provides this API for direct use. But in real projects, we do it again in order to make the code easier to maintain and reduce our code volume. So let’s look at what we need to do to encapsulate the request

  1. Since there is no AXIos request blocking API, we need to do some global judgments and Settings before actually requesting:

Request URL, custom request header, request timeout, login or not, set Content-Type according to request mode, and parameter escape 2. Successful failure and no response after a successful request Default action 3. Reorganization of the corresponding data structure returned to the API request

import operate from '.. /common/operate.js' // Domain name of the interface address
/ / vuex use Details refer to the website https://uniapp.dcloud.io/vue-vuex
import store from '.. /store/index.js'  

export default class Request {
    http(param) {
		let token = store.getToken() || ""
		if(! token) {// There is no token authentication logic
		}
        // Request parameters
        var url = param.url,
            method = param.method,
            header = {},
            data = param.data || {},
            hideLoading = param.hideLoading || false;

        // Concatenate the full request address
        var requestUrl = operate.api + url;

        // Request mode :GET or POST(POST needs to be configured
        // header: {'content-type' : "application/x-www-form-urlencoded"},)
        if (method) {
            method = method.toUpperCase(); // Change lowercase to uppercase
            if (method == "POST") {
                header = {
                    'content-type': "application/x-www-form-urlencoded"
                };
            } else {
                header = {
                    'content-type': "application/json"}; }}/ / load
        if(! hideLoading) { uni.showLoading({title: 'Loading... '
            });
        }

        / / return promise
        return new Promise((resolve, reject) = > {
            / / request
            uni.request({
                url: requestUrl,
                data: data,
                method: method,
                header: header,
                success: (res) = > {
                    // Determine if the request API format is correct
                    if(res.statusCode && res.statusCode ! =200) {
                        uni.showToast({
                            title: "API error" + res.errMsg,
                            icon: 'none'
                        });
                        return;
                    }
                    // code judgment :200 success does not equal 200 error
                    if (res.data.code) {
                        if(res.data.code ! ='200') {
                            uni.showToast({
                                title: "" + res.data.msg,
                                icon: 'none'
                            });
                            return; }}else {
                        uni.showToast({
                            title: "code! = 200" + res.data.msg,
                            icon: 'none'
                        });
                        return;
                    }
                    // Throw the result
                    resolve(res.data)
                },
                // The request failed
                fail: (e) = > {
                    uni.showToast({
                        title: "" + e.data.msg,
                        icon: 'none'
                    });
                    resolve(e.data);
                },
                // Request completed
                complete() {
                    // Hide the load
                    if(! hideLoading) { uni.hideLoading(); } resolve();return; }})})}}Copy the code

How are UI components introduced

In actual business projects, third-party plug-ins are often used. If the project is installed with VUE-CLI, it can be directly installed with NPM and then introduced to use. However, if the project is created using HBuilder, you need to refer to easycom component specification to import components before using them

Easycom component specification

Traditional VUE components require three steps of installation, reference, and registration before they can be used. Easycom reduces this to a single step. As long as the component is installed in the components or uni_modules directory of the project and conforms to the components/ component name/component name.vue directory structure. It can be used directly on the page without reference or registration.

No matter how many components are installed in the Components directory, easyCom packages and automatically removes unused components, making the component library especially user-friendly.

How to use components that do not meet easyCOM specifications

  1. Method 1: If your component name or path does not conform to easyCom’s default specification,

Personalization can be carried out in the easycom node of pages. Json to customize the strategy of matching components

"easycom": {
  "autoscan": true.// Enable scanning
  "custom": {
    "^uni-(.*)": "@/components/uni-$1.vue".// Match the vue file in the Components directory
    "^vue-file-(.*)": "packageName/path/to/vue-file-$1.vue" // Matches the vue file in node_modules}}Copy the code
  1. The second method: directly using vUE’s component reference method can also be satisfied, component installation reference registration

Pay attention to

The EasyCOM component specification can only satisfy components of vUE files, not components of other file formats