使用wepy開發微信小程式01——常用的元件

阿炬發表於2018-06-13

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
})

 

相關文章