Preliminary summary of uniAPP use

I. Project initialization

Follow the official documentation

Uni-ui/UNI-app templates are recommended, depending on your needs.

Minor changes to the file directory (personal likes and dislikes)

  1. File Directory Description
  • Config folder: Centrally manages configurable information and variables
  • Globaldata.js: global variable unified management file (equivalent to vuex);
  1. Servers file: Interface request service management folder;
  • Apis folder: Request request encapsulation management and interface API configuration management folder.
  • Request.js: a Promise wrapper for wx.request;
  • Xxx.js: interface management file of the corresponding module;
  • Requestfilter.js: interface request and response interception encapsulates files;
  1. Little else can be said

UI Framework Recommendation

Individual recommendation uViewUI depends on individual needs

The interface encapsulates the request

There are many packaged components in the UNIApp plug-in market for personal preference. Personally, I recommend using PROMISE for self-packaging to ensure subsequent controllability and maintenance, and refer to AXIos for packaging

request.js


import formatError from "./requestFilter"
const app = getApp()
const request = (method, url, data) = > {
	// Set the request header
	const header = {

	}
	// Promise encapsulates a layer that is received directly with then and catch when invoked
	return new Promise((resolve, reject) = > {
		uni.request({
			method: method,
			url: app.globalData.host + url, // complete host
			data: data,
			header: header,
			success(res) {
				// Perform data management and unified logic operations on successfully returned requests
				if (res.statusCode === 200) { // The request returned successfully
					if (res.data && res.data.code === "SUCCESS") { // The back end processes the interface request successfully and returns data to the interface caller
						resolve(res.data) / / then receive
					} else { // The backend pair also requests an error that is considered illogical
						formatError(res) // Unified error handling logic
						reject(res.data) / / catch}}else {
					reject(res.data) / / catch}},fail(err) {
				uni.showToast({
					title: 'Network exception, try again later! '.mask: true.icon: 'none'.duration: 3000})})})}export default request;

Copy the code

The specific use

To the user. The js, for example

import request from ".. /request";

// Get user openID
export const usrInfos = data= > request("POST"."/user/usrInfos", data);
Copy the code

Page calls

<script>
	import { usrInfos } from ".. /.. /servers/apis/user"
	export default {
		data() {
			return {
				href: 'https://uniapp.dcloud.io/component/README? id=uniui'}},methods: {
			login(){
				usrInfos().then(res= >{})}},onLoad() {
			this.login()
		}
	}
</script>
Copy the code

Interface request interception and corresponding interception encapsulation

Note: interception requires clear interface return field format and agreed return code specification

requestFilter.js

/** * Format the backend error returned by the interface *@param {data successfully returned by the interface} res 
 */
const formatError = (err) = >{
  uni.showToast({
    title: err.message,
    mask: false.icon: 'none'.duration: 3000})};export default formatError;

Copy the code

Iv. Data management

Uniapp global variable dependencies: Vuex or globalData is recommended for links. I’m using globalData for applets

Official: There is a globalData concept in the applet that allows you to declare global variables on the App. Vue did not have such concepts before, but Uni-App introduced globalData concepts and implemented them on platforms including H5, APP, etc.

It is unknown whether there are compatibility problems on multiple platforms in the future

globalData.js

export default {
	host: "http://www.wawow.xyz/api/test".// The domain name and prefix of the interface requested by the interface

}

Copy the code

mount

import Vue from 'vue'
import App from './App'
import globalData from './config/globalData.js'
Vue.config.productionTip = false

App.mpType = 'app'
App.globalData = globalData
const app = newVue({ ... App }) app.$mount()Copy the code

5. Encapsulation of public methods (recommended in 2)

Method 1. Mount it to the VUE instance

import Vue from 'vue'
// import store from '.. /store';
// Stores in uni do not need to be registered in the new Vue of main.js
// Vue.prototype.$store = store;


Vue.prototype.$toast = (title, duration = 1500) = > uni.showToast({
	icon: 'none',
	title,
	duration
})

Copy the code

The main mount in js

import Vue from 'vue'
import App from './App'
import globalData from './config/globalData.js'
require('./utils/utils.js')
Vue.config.productionTip = false

App.mpType = 'app'
App.globalData = globalData
const app = newVue({ ... App }) app.$mount()Copy the code

Method 2. Ordinary JS, using page import

const pluginFun=function(){
	console.log('This is the method in plugin')}module.exports={
	pluginFun:pluginFun
}
Copy the code

Comparison: this.xx () can be called directly in method 1, but it is not recommended to mount too many methods on the vue instance. Specific reasons can be found in Baidu method 2, which needs to import XX every time it is used, adding the tedious summary during the call:

  1. High usage Mode 1
  2. Use mode 2 of some pages, such as form verification method

Code address link