扩展mpx
小程序api promisify:@mpxjs/promisify(已废弃,推荐使用新的)小程序API转换及promisify:@mpxjs/api-proxy 详细介绍
开发插件
mpx支持使用mpx.use使用插件来进行扩展。插件本身需要提供一个install方法或本身是一个function,该函数接收一个proxyMPX。插件将采用直接在proxyMPX挂载新api属性或在prototype上挂属性。需要注意的是,一定要在app创建之前进行mpx.use
扩展: test.js
import test from './test'
mpx.use(test)
mpx.createApp({
onLaunch() {
mpx.newApi() // out put: "is new api"
this.testHello() // output: 'hello'
}
})
小程序request存在不限域名的并发限制,因此封装一个fetch来处理这种缺陷,能支持请求优先级,同时fetch还支持拦截器,请求取消等等
使用说明
import mpx from '@mpxjs/core'
import mpxFetch from '@mpxjs/fetch'
mpx.use(mpxFetch)
// 第一种访问形式
mpx.xfetch.fetch({
url: 'http://xxx.com'
}).then(res => {
console.log(res.data)
})
mpx.createApp({
// 第二种访问形式
this.$xfetch.fetch({url: 'http://test.com'})
}
})
导入api说明
mpx-fetch提供了一个实例 xfetch ,该实例包含以下api
- fetch(config, priority), 正常的promisify风格的请求方法, priority表示请求优先级(normal,low),默认为normal
- addLowPriorityWhiteList(rules), 按域名规则设置低优先级请求的白名单,接收一个参数,可以是字符串,也可以是正则表达式,也可以是数组 (如果fetch传入了第二个参数,那么无视这个白名单)
- CancelToken,实例属性,用于创建一个取消请求的凭证。
- create(), 用于创建一个新的mpx-fetch实例
- interceptors,实例属性,用于添加拦截器,包含两个属性,request & response
mpx.xfetch.fetch({
url: 'http://xxx.com',
data: {
name: 'test'
}
}, 'low')
// or addSignWhiteList
mpx.xfetch.addLowPriorityWhiteList('http://xxx.com')
请求拦截器
请求中断
const cancelToken = new mpx.xfetch.CancelToken()
url: 'http://xxx.com',
data: {
name: 'test'
},
cancelToken: cancelToken.token
})
cancelToken.exec('手动取消请求') // 执行后请求中断,返回abort fail
mpx.xfetch.fetch({
url: 'http://xxx.com',
method: 'POST',
data: {
name: 'test'
},
emulateJSON: true // 等价于header = {'content-type': 'application/x-www-form-urlencoded'}
})
支持 params
mpx.xfetch.fetch({
url: 'http://xxx.com',
params: {
name: 'test'
}
})
mpx.xfetch.fetch({
url: 'http://xxx.com',
params: {
age: 10
},
data: {
name: 'test'
},
emulateJSON: true // 等价于header = {'content-type': 'application/x-www-form-urlencoded'}
})
自动过滤值为undefined和null的属性,其中null未转换成空字符串
API-PROXY
// 单独使用
apiProxy(target, options) // target 为要抹平的对象
Options
普通形式
import mpx from '@mpxjs/core'
import apiProxy from '@mpxjs/api-proxy'
mpx.use(apiProxy, {
exclude: ['showToast'] // showToast 将不会被转换为目标平台
})
mpx.showModal({
title: '标题',
content: '这是一个弹窗',
success (res) {
if (res.cancel) {
console.log('用户点击取消')
}
}
})
使用promise形式
import mpx from '@mpxjs/core'
import apiProxy from '@mpxjs/api-proxy'
mpx.use(apiProxy, {
usePromise: true
})
mpx.showActionSheet({
itemList: ['A', 'B', 'C']
})
.then(res => {
console.log(res.tapIndex)
})
.catch(err => {
console.log(err)
})
Mock
mock数据生成规则同mockjs