1、axio.js
'use strict'
import axios from 'axios'
import wepyAxiosAdapter from 'wepy-plugin-axios/dist/adapter.js'
const instance = axios.create({
adapter: wepyAxiosAdapter(axios),
baseURL: 'https://API_HOST/api',
headers: {
'Authorization': undefined
},
validateStatus: () => true
})
export default instance
let token = ''
export function getToken () { return token }
export function setToken (newToken) {
token = newToken
instance.defaults.headers['Authorization'] = 'Bearer ' + token
}
2、util.js
'use strict'
import * as d3TimeFormat from 'd3-time-format'
/** 解析日期 */
function parseDate (date) {
let d = new Date(date)
if (Number.isNaN(+d)) {
d = new Date()
}
return d
}
/** 只保留一个日期的年、月、日 */
export function trimDate (date) {
const d = parseDate(date)
return new Date(d.getFullYear(), d.getMonth(), d.getDate())
}
// 预定义的日期时间格式
const dateFormat = d3TimeFormat.timeFormat('%Y-%m-%d')
const timeFormat = d3TimeFormat.timeFormat('%H:%M')
/** 格式化日期 */
export function formatDate (date) {
const d = parseDate(date)
return dateFormat(d)
}
/** 格式化时间 */
export function formatTime (date) {
const d = parseDate(date)
return timeFormat(d)
}
/** 生成用于表单绑定的 change 函数 */
export function generateChangeMethods (parent, props) {
const result = {}
props.forEach(prop => {
result[prop + 'Changed'] = function (e) {
this[parent][prop] = e.detail.value
}
})
return result
}
3、wepy.js
'use strict'
import wepy from 'wepy'
import axios from './axios'
import events from './events'
export function $modal (title, content, showCancel = false) {
return wepy.showModal({
title,
content,
showCancel
}).then(data => data.confirm)
}
export function $loading (title, mask = true) {
if (title) {
return wepy.showLoading({ title, mask })
} else {
return wepy.hideLoading()
}
}
export const $http = axios
export function $navigateTo (key, url) {
if (key && !url) {
url = key
key = undefined
}
return wepy.navigateTo({ url }).then(() => key && new Promise(resolve => events.once(key, resolve)))
}
export function $navigateBack (key, ...args) {
if (key) {
events.emit(key, ...args)
}
return wepy.navigateBack()
}
Object.assign(wepy.component.prototype, {
$modal,
$loading,
$http,
$navigateTo,
$navigateBack,
$globalEvents: events
})