使用wepy开发微信小程序01——常用的组件

2018-06-24 02:16:36来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:使用chrome开发者工具中的network面板测量网站网络性能

下一篇:5分钟了解TypeScript