1.0.8 • Published 6 years ago

zls-wxa-run v1.0.8

Weekly downloads
3
License
ISC
Repository
-
Last release
6 years ago

小程序API接口平滑调用

需求

因小程序迭代太快了,很多接口都要兼容处理。

依赖

需要 async-await 支持

如不熟悉如何小程序使用,建议直使用wepy。

wepy

async-await

示例脚手架

请先安装构建工具 - zls-cli

npm install -g zls-cli

zls new wepy-template ProjectFolder

cd ProjectFolder

npm run dev

初始化

重要: 引入之后要记得执行初始化

interfaces.init(wepy)

参说明数

wepy: wepy对象/支持Promise的微信接口对象(看底下说明)

ps. 那天微信接口直接支持 Promise 了,就直接把 wx 实例直接丢进入就好了。


执行API接口

interfaces.run(name, args = [])

参说明数

name: 接口名

args: 接口传参(数组)

let location
try {
    location = WxaRun.run(wepy, 'getLocation', 'scope.userLocation', 1, { content: '请允许地理位置', showCancel: true }, '请允许地理位置')
}catch ( type, msg ) {
    //type == 'warning',版本过低
    //type == 'fail',执行失败
}

执行需要权限判断的API接口

interfaces.authRun(name, args = [], scope = null, must = 1, tip = {}, errorText = {})

参说明数

name: 接口名

args: 接口传参(数组)

scope: scope(包含scope.)/false(执行方式只支持1,0)

must: 执行方式 -1:必须开启权限执行(必须设置scope)/0:静默执行没有权限不提示/1:没权限下提并跳去开启

tip: 没有权限时候的提示弹窗/false不显示弹窗

errorText: 开启权限失败的提示弹窗/false不显示弹窗

返回值 Promise


登录授权

interfaces.login(must = 1, tip = {}, errorText = {})

参说明数

must: 执行方式 -1:必须开启权限执行(必须设置scope)/0:静默执行没有权限不提示/1:没权限下提并跳去开启

tip: 没有权限时候的提示弹窗/false不显示弹窗

errorText: 开启权限失败的提示弹窗/false不显示弹窗

返回值 Promise


示例

获地理位置

import wepy from 'wepy'
import 'wepy-async-function'
import WxaRun from './components/login_relogin.js'

WxaRun.init(wepy)


//...methods
let location
try {
    location = WxaRun.run(wepy, 'getLocation', 'scope.userLocation', 1, { content: '请允许地理位置', showCancel: true }, '请允许地理位置')
}catch ( type, msg ) {
    //type == 'warning',版本过低
    //type == 'fail',执行失败
}

Promise化微信接口

可能有些人更喜欢原生小程序的写法,可以自己把微信接口Promise化

话说 ,现在微信好像移除了 promise , 建议自己加上 es6-promise

promise.util.js

module.exports = {
  promisify: (api) => {
    return (options, ...params) => {
      return new Promise((resolve, reject) => {
        const extras = {
          success: resolve,
          fail: reject
        }
        api({ ...options, ...extras }, ...params)
      })
    }
  }
}

page.js

import promiseUtil from './promise.util'

var getLocationPromisified = promiseUtil(wx.getLocation)

getLocationPromisified({
  type: 'wgs84'
}).then(function (res) {
 console.log(res)
}).catch(function () {
  console.error("get location failed")
})
1.0.8

6 years ago

1.0.6

6 years ago

1.0.5

6 years ago

1.0.3

6 years ago

1.0.2

6 years ago

1.0.1

6 years ago

1.0.0

6 years ago

0.0.1

6 years ago