The article introduces

  1. General tool method, global data
  2. All methods, computed properties defined below, will be mounted to this on all.vue pages

Note: In the small program side, the computed properties will be mounted in the form of data objects to the Page object of all pages. Therefore, in case of large amount of data, please use the form of dynamic fetching by calling methods to optimize performance and avoid too much memory

(1) onBackPress

Introduction: [App Platform] Click the back button to remove Loading, to prevent a page error press the back button and loading

// #ifdef app-vue onBackPress() {uni.hideloading ()} // #endif ---- End conditional compilationCopy the code

methods

Route jump class method

SET_PARAM (2)

Introduction: Staging a cross-page variable (paired with GET_PARAM)

 SET_PARAM(val) {
	this.SET_GLOBAL('pageParam', val)
    }
Copy the code

(3) the GET_PARAM

Introduction: Getting previously staged cross-page variables (paired with SET_PARAM)

 GET_PARAM() {
	return this.GET_GLOBAL('pageParam')
     }
Copy the code

(4) NAV_TO

Introduction: A page is displayed

NAV_TO(url, param, usePageParam) {
	uni.navigateTo({
		url: this.handleNav(url, param, usePageParam)
	  })
    }

Copy the code

(5) NAV_BACK

Introduction: return to the previous page —- The delta parameter is the number of times to return

NAV_BACK(delta = 1) {
	uni.navigateBack({
		delta
	 })
   }
Copy the code

(6) JUMP_TO

Introduction: Jump to a page, jump after cannot return

JUMP_TO(url, param, usePageParam) {
	uni.redirectTo({
	url: this.handleNav(url, param, usePageParam)
        })
   }
Copy the code

(7) TAB_TO

Introduction: Go to a Tab page

TAB_TO(url, param) {
	uni.switchTab({
	url: this.handleNav(url, param, true)
        })
  }
Copy the code

RELAUNCH_TO (8)

Introduction: Restart the application and go to the specified page

RELAUNCH_TO(url) {
	uni.reLaunch({
	url
	})
 }
Copy the code

(9) GET_GLOBAL

Get a global variable —-key as the key name

GET_GLOBAL(key) {
	return this.$store.state[key]
 }
Copy the code

SET_GLOBAL (10)

Set a global variable —-key to the key name —-val

SET_GLOBAL(key, val) {
	this.$store.commit(key, val)
 }
Copy the code

CLEAR_GLOBAL (11)

Clearing global variables

CLEAR_GLOBAL() {
	this.$store.commit('clear')
	uni.removeStorageSync('token')
 }
Copy the code

SET_STORAGE (12)

Writing data to a local cache

SET_STORAGE(key, data) {
	if (data === null) {
		uni.removeStorageSync(key)
	} else {
		uni.setStorageSync(key, data)
	}
 }
Copy the code

GET_STORAGE (13)

Description: Obtain data previously written to the local cache

GET_STORAGE(key) {
	return uni.getStorageSync(key)
 }
Copy the code

CLEAR_STORAGE (14)

Clearing the local cache

CLEAR_STORAGE() {
	uni.clearStorageSync()
 }
Copy the code

Prompt box class method

(15) TOAST

Introduction: The display prompt box —-title is the prompt text —-mask is whether to forbid clicking —-icon is the display icon, which can be changed to ‘success’

TOAST(title, icon = 'none', mask = false) {
	uni.showToast({
		title,
		icon,
		mask
	})
 }
Copy the code

HIDE_TOAST (16)

Introduction: Stop displaying the Toast prompt box

HIDE_TOAST() {
	uni.hideToast()
 }
Copy the code

(17) LOADING

Description: The loading prompt box —-title is displayed as the prompt text —-mask is displayed as whether to disable clicking

LOADING(title, mask = true) {
	uni.showLoading({
		title,
		mask
	})
 }
Copy the code

HIDE_LOADING (18)

Description: Stop displaying the loading prompt box

HIDE_LOADING() {
	uni.hideLoading()
 }
Copy the code

CONFIRM (19)

Description: Display a confirmation dialog box —-title indicates the title —- Content indicates the content of the dialog box —-showCancel indicates whether to display the cancel button

async CONFIRM(title, content, showCancel = false) {
	return new Promise(res => {
		uni.showModal({
			title,
			content,
			showCancel,
		success: ({
			confirm
		    }) => {
			res(confirm)
		     },
		fail: () => {
			res(false)
		     }
		})
	   })
  }
Copy the code

Global event class methods

SET_TITLE (20)

Description: Set the page title

SET_TITLE(title) {
	uni.setNavigationBarTitle({
		title
	})
 }
Copy the code

The CONFIG (21)

Introduced: from/config. Js to get one of the configuration items, if in the/config. Can’t get in js, headed to/common/config. The default. The access to the default value of js – access path of the path for the configuration items

This.config (‘ pageconFig. roundAvatar’)

CONFIG(path) {
	return get(globalConfig, path, get(defaultConfig, path))
 }
Copy the code

(22) ON

Description: Listen for a global event

ON(name, func) {
	uni.$on(name, func)
 }
Copy the code

ONCE (23)

Introduction: Listen for only one global event at a time

ONCE(name, func) {
	uni.$once(name, func)
 }
Copy the code

EMIT (24)

Description: Triggers a global event

EMIT(name, data) {
	uni.$emit(name, data)
 }
Copy the code

(25) OFF

Description: Remove a global event listener

OFF(name, func) {
	uni.$off(name, func)
 }
Copy the code

Pulls the specified data class method

FETCH_DATASOURCE (26)

Pull data source with specified code value

async FETCH_DATASOURCE(code) { if (! code) { return [] } return await this.HTTP_GET('/datasource/map', { code, ver: '' }) }Copy the code

FETCH_ENCODE (27)

Introduction: Pull the form code data with the specified rule number

async FETCH_ENCODE(rulecode) { if (! rulecode) { return '' } return await this.HTTP_GET('/coderule/code', rulecode) }Copy the code

FETCH_FILEINFO (28)

Introduction: Pull the file information with the specified ID

async FETCH_FILEINFO(fileId) { if (! fileId) { return null } return await this.HTTP_GET('/annexes/wxfileinfo', fileId) }Copy the code

Request class method

HTTP_GET (29)

Introduction: Encapsulated GET request, integrated authentication information, return request result or null, network error, return error code, login status invalid and other cases to do the corresponding processing, URL for the request address, data for the request submitted data

async HTTP_GET(url, data, showTips) {
	const [err, res] = await this.requestBase(url, data, null, 'GET')
		return this.handleResult(err, res, showTips)
 }
Copy the code

HTTP_POST (30)

Introduction: Encapsulated POST request, integrated authentication information, return request result or null, network error, return error code, login status invalid and other cases to do the corresponding processing, URL for the request address, data for the request submitted data

async HTTP_POST(url, data, showTips) {
	const [err, res] = await this.requestBase(url, data, null, 'POST')
                return this.handleResult(err, res, showTips)
 }
Copy the code

The GET (31)

Introduction: Make a GET request, encapsulate authentication, url is the address of the request, data is the submitted data attached to the request, and the result is an array: [error, result], error indicates an error, usually a network error, and the request may not be sent at all. Result contains {statusCode, headers, data}, indicating the statusCode, response head, and data, respectively

async GET(url, data, header) {
	return await this.requestBase(url, data, header, 'GET')
 }
Copy the code

(32) POST

Introduction: Make a POST request, encapsulate authentication, url is the request address, data is the submitted data attached to the request, and the result is an array: [error, result], error indicates an error, usually a network error, and the request may not be sent at all. Result contains {statusCode, headers, data}, indicating the statusCode, response head, and data, respectively

async POST(url, data, header) {
	return await this.requestBase(url, data, header, 'POST')
 }
Copy the code

File upload and download class method

HTTP_UPLOAD (33)

Description: Encapsulated file upload, integrated authentication information, return interface return value or null, network error, return error code, invalid login status and other cases to do the corresponding processing, URL is the request address, filePath is the path of the temporary file, formData is submitted data attached to the request

async HTTP_UPLOAD(filePath, formData) {
	const [err, res] = await this.UPLOAD('/annexes/wxupload', filePath, formData)
        return this.handleResult(err, res)
 }
Copy the code

HTTP_DOWNLOAD (34)

Introduction: encapsulated file download, integrated authentication information, return interface return value or null, network error, return error code, login status invalid and other cases to do the corresponding processing, URL for the request address, formData for the request submitted data

async HTTP_DOWNLOAD(formData) {
	const [err, res] = await this.DOWNLOAD('/annexes/wxdown', formData)
        return this.handleResult(err, res)
 }
Copy the code

(35) the UPLOAD

Introduction: FilePath is the path to the local temporary file, formData is the parameter attached to the upload, and the result is an array: [error, result], error indicates an error, usually a network error, and the request may not be sent at all. Result contains {statusCode, data}, which respectively indicates the statusCode and the data returned by the interface

async UPLOAD(url, filePath, formData) { const uploadUrl = this.handleUrl(url) const query = { loginMark: this.getLoginMark(), token: this.GET_GLOBAL('token') } if (formData && typeof formData === 'object') { Object.assign(query, formData) } else if (typeof formData === 'string') { Object.assign(query, { data: Return new Promise((res, rej) => {dd. UploadFile ({url: uploadUrl, filePath, fileName: 'file', fileType: 'image', formData: query, success: dt => { dt.data = JSON.parse(dt.data) res([null, dt]) }, fail: {rej([rs, null])}})}) // #endif // #ifndef mp-dingtalk ---- uploadUrl, filePath, name: 'file', fileType: 'image', formData: query }).then(([err, result]) => { if (! err) { result.data = JSON.parse(result.data) return [null, result] } else { return [err, null] } }) // #endif }Copy the code

The DOWNLOAD (36)

Introduction: Download a file (temporary) that encapsulates authentication, the URL is the address of the request, the formData is the parameters attached to the request, and the result is an array: [error, result], error indicates an error, usually a network error, and the request may not have been made at all. Result contains {statusCode, tempFilePath}, which indicates the statusCode and the path of the temporary file after downloading

async DOWNLOAD(url, formData) { let downloadUrl = this.handleUrl(url) const query = {} if (formData && typeof formData === 'object') { Object.assign(query, formData) } else if (typeof formData === 'string') { Object.assign(query, { data: formData }) } downloadUrl = downloadUrl + '? ' + this.URL_QUERY(query, true) return uni.downloadFile({ url: downloadUrl }).then(([err, result]) => { if (! err) { result.data = { data: result.tempFilePath } result.statusCode = 200 } return [err, result] }) }Copy the code

Pull global client data

FETCH_CLIENTDATA (37)

Introduction: Pull global data from the client and write global variables directly

async FETCH_CLIENTDATA() {
    await Promise.all([
	this.HTTP_GET('/company/map').then(res => this.SET_GLOBAL('company', res.data || {})),
	this.HTTP_GET('/department/map').then(res => this.SET_GLOBAL('department', res.data ||         {})),
	this.HTTP_GET('/user/map').then(res => this.SET_GLOBAL('user', res.data || {})),
	this.HTTP_GET('/dataitem/map').then(res => this.SET_GLOBAL('dataDictionary', res.data           || {}))
	])
  }
Copy the code

Common front end methods

COPY (38)

Using JSON serialization to clone an object or array

COPY(val) {
	return JSON.parse(JSON.stringify(val))
 }
Copy the code

GUID (39)

JoinChar: a 32-bit random GUID string is generated. JoinChar is the separator and the default value is underscore

GUID(joinChar = '_') { return `xxxxxxxx${joinChar}xxxx${joinChar}4xxx${joinChar}yxxx${joinChar}xxxxxxxxxxxx`.replace(/[xy]/g, c => { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); })}Copy the code

The MD5 (40)

Description: Obtains the MD5 code of a specified string

MD5(val = '') {
	return md5(val)
 }
Copy the code

TABLEITEM_DATEFORMAT (41)

DatetimeString is the date and time string to be formatted. The return value is an array. It can also be used as a string

For example:

  1. Returns if the date is the same day[' today when]or'today when'
  2. If the date is this year, return[' June 8 ', '17:32']or'17:32, 8th June'
  3. If the date is not this year, return[' 2018-06-08 ']or'2018-06-08'
TABLEITEM_DATEFORMAT(datetimeString) { const dt = moment(datetimeString) let result = [] if (! dt.isValid()) { result.toString = () => '' return result } const now = moment() if (dt.isSame(now, "Day")) {result = [` today ${dt. The format (' HH: mm)} `] result. The toString () = = > ` today ${dt. The format (' HH: mm)} `} else if (dt. IsSame (now, "year")) {result = [dt. The format (' on D M), Dt. format('HH:mm')] result.toString = () => dt.format('HH:mm') + "+ dt.format('HH:mm')} else {result = [dt.format('YYYY-MM-DD')] result.toString = () => dt.format('YYYY-MM-DD') } return result }Copy the code

URL_QUERY (42)

Obj is the object to be converted. If the value is null, it will be ignored. If the value is an object, it will be converted to a JSON string

URL_QUERY(obj, auth = false) {
        let queryObject = obj || {}
        if (typeof obj === 'string') {
                queryObject = {
                        data: obj
                }
        }
        if (auth) {
                Object.assign(queryObject, {
                        loginMark: this.getLoginMark(),
                        token: this.GET_GLOBAL('token')
                })
        }
        return Object.entries(queryObject)
                .filter(([k, v]) => k && v)
                .map(([k, v]) => encodeURIComponent(k) + '=' + encodeURIComponent(typeof v === 'object' ? JSON.stringify(v) : v))
                .join('&')
 }
Copy the code

CONVERT_HTML (43)

Introduction: Converting strings to HTML (HTML for processing form pages)

CONVERT_HTML(str) { if (! str) { return '' } return str .replace(/{@zuojian@}|{@youjian@}|{@and@}/g, tag => ({ '{@zuojian@}': '<', '{@youjian@}': '>', '{@and@}': '&' })[tag] || tag) .replace(/&amp; |&lt; |&gt; | & # 39; |&quot; /g, tag => ({ '&amp; ': '&', '&lt; ': '<', '&gt; ':' > ', '& # 39; ': "'", '&quot; ': '"' })[tag] || tag) }Copy the code

MP_SHARE_ENCODE (44)

Introduction: The url query string used to encode the small program to share the message (it will also be printed in the development environment), pageParam is the pageParam carried when clicking to share the message jump, Query is the Query carried when clicking to share the message jump, PagePath Click the share message to jump to the page of the applets (default is the current page) and return the encoded query string

MP_SHARE_ENCODE(pageParam, query, pagePath) { const shareObj = { fromUser: this.GET_GLOBAL('loginUser').userId, fromPlatform: this.PLATFORM, timestamp: new Date().valueOf(), pagePath: pagePath || this.pagePath, query: query, pageParam, learun: This.app_version} const result = this.url_query (shareObj) if (this.dev) {console.log(' [you are sharing a small program page]] ') The console. The log (' = = = = Shared object: = = = = ') console. The log (shareObj) console. The log (' = = = = start path: . = = = = ') the console log ('/pages/home) console. The log (" = = = = launch parameters: . = = = = ') the console log (result) console. The log (' = = = = (above message development patterns visible only) = = = = ')} return result}Copy the code

MP_SHARE_DECODE (45)

Introduction: parsing small program sharing string (will automatically adapt the URL coding of micro channel small program), micro channel small program sharing information is obtained by URL encoding, need to decode; Alipay/Nail mini program does not need decoding

MP_SHARE_DECODE(info) { // #ifdef MP-WEIXIN const shareInfo = mapValues(info, decodeURIComponent) // #endif shareInfo.pageParam = shareInfo.pageParam ? JSON.parse(shareInfo.pageParam) : undefined shareInfo.query = shareInfo.query ? this.URL_QUERY(JSON.parse(shareInfo.query)) : Undefined if (this.dev) {console.log(' [you started the applet with the applet message sharing] ') console.log('==== applet sharing object: ====') console.log(shareInfo) console.log('==== about to go to the page: ====') console.log(shareinfo.pagepath) console.log('==== set url query: ====') console.log(shareinfo.query) console.log('==== set pageParam: ====') console.log(shareinfo.pageparam) console.log('====(above message visible only in development mode)====')} this.set_global ('pageParam', shareInfo.pageParam) uni.navigateTo({ url: `${shareInfo.pagePath}? ${this.URL_QUERY(shareInfo.query)}` }) }Copy the code

Internal methods

HandleNav (46)

Description: Handle the page jump URL and parameters

handleNav(url, param, usePageParam) { let query = '' if (param && usePageParam) { this.SET_PARAM(param) } else if (param && ! usePageParam) { query += '? ' + Object.entries(param).filter(([k, v]) => k && v).map(([k, v]) => k + '=' + v).join('&') } return url + query }Copy the code

GetLoginMark (47)

The loginMark device id is obtained from the global variable and cache. If the device id is not obtained, a new one is generated

getLoginMark() { if (this.GET_GLOBAL('loginMark')) { return this.GET_GLOBAL('loginMark') } const storageData = uni.getStorageSync('loginMark') if (storageData && storageData ! == 'null' && storageData ! == 'undefined') { this.SET_GLOBAL('loginMark', storageData) return storageData } const newLoginMark = this.GUID() this.SET_GLOBAL('loginMark', newLoginMark) uni.setStorageSync('loginMark', newLoginMark) return newLoginMark }Copy the code

HandleUrl (48)

Description: Process the URL to determine whether to add the background address prefix

handleUrl(url) { let result = url if (result.startsWith('http://') || result.startsWith('https://')) { return result } if (! result.startsWith(this.API)) { result = this.API + result } return result }Copy the code

RequestBase (49)

Introduction: Basic methods of HTTP request

async requestBase(url, data, header, method = 'GET') { const requestUrl = this.handleUrl(url) const requestHeader = header || {} let requestData = { loginMark: this.getLoginMark(), token: this.GET_GLOBAL('token') || '' } if (data && typeof data === 'object') { requestData.data = JSON.stringify(data) } else if (data) { Object.assign(requestData, { data }) } return uni.request({ url: requestUrl, method, header: { 'content-type': 'application/x-www-form-urlencoded', ... requestHeader }, data: requestData }) }Copy the code

HandleResult (50)

A method for handling network requests returns results

HandleResult (err, result, tips) {/ / there is an error, the general is a network connection error if (err | |! Result) {uni.hideloading () uni.showtoast ({title: 'Network request failed, please check your network connection ', icon: }) return null} Login state failure if (result. StatusCode = = = 410 | | (result. The data && result. The data. The code = = = 410)) {uni. HideLoading (uni). ShowToast ({ Title: 'Invalid login status, jumping to login page... ', icon: 'none' }) this.CLEAR_GLOBAL() uni.reLaunch({ url: '/pages/login' }) return null uni.hideLoading() if (tips) { const errInfo = (result.data && result.data.info) || '(unknown cause)' const errTips = typeof tips === 'string'? Tips: 'Error occurred while requesting data' uni.showtoast ({title: '${errTips} : ${errInfo}', icon: 'None'})} return null} return result.data.data}Copy the code

computed

(51) API

Description: Request the address of the background interface

API() {
        return this.$store.state.apiRoot ||this.CONFIG('apiHost')[this.DEV ?this.CONFIG('devApiHostIndex') : this.CONFIG('prodApiHostIndex')]
 }
Copy the code

(52) PATH

Description: Path of the current page

PATH() { if (! getCurrentPages) { return '' } const pages = getCurrentPages() return pages ? '/' + pages.slice(-1)[0].route : '' }Copy the code

DEV (53)

Description: Is the current development environment

DEV() {
        return process.env.NODE_ENV === 'development'
 }
Copy the code

DEV_ONLY_GLOBAL (54)

Introduction: [development mode only] get the current global variable, invalid in production environment, official release, because the small program side global variable will be mounted to each page, affecting performance

DEV_ONLY_GLOBAL() {
        return process.env.NODE_ENV === 'development' && this.$store.state
 }
Copy the code

APP_VERSION (55)

Get the current mobile version number (defined in config.js)

APP_VERSION() {
        return this.CONFIG('appVersion')
 }
Copy the code

(56) PLATFORM

Introduction: Current operating platform, value ‘alipay’/weixin’/’dingtalk’/’h5’/’app’/’ unknown ‘

PLATFORM() {
        let result = 'unknow'

        // #ifdef MP-ALIPAY
        // #ifndef MP-DINGTALK
        result = 'alipay'
        // #endif
        // #ifdef MP-DINGTALK
        result = 'dingtalk'
        // #endif
        // #endif

        // #ifdef MP-WEIXIN
        result = 'weixin'
        // #endif

        // #ifdef H5
        result = 'h5'
        // #endif

        // #ifdef APP-VUE
        result = 'app'
        // #endif

        return result
 }
Copy the code

PLATFORM_TEXT (57)

Introduction: To obtain the full Chinese name of the current operating platform, the value is’ Alipay applet ‘/ wechat applet ‘/’ Nail Applet ‘/’ mobile H5 ‘/’ mobile App’/’ (unknown) ‘

PLATFORM_TEXT() {let result = '#ifdef mp-alipay' // #ifndef mp-dingtalk result = '#endif' // #ifdef // #endif // #ifdef mp-weixin result = 'wechat small program' // #endif // #ifdef H5 result = 'wechat small program' // #endif // #ifdef H5 result = #ifdef app-vue result = 'mobile phone APP' // #endif return result} #ifdef app-vue result = 'mobile phone APP' // #endif return result}Copy the code