github地址:https://github.com/wendux/fly
flyio是個(gè)跨平臺(tái)的網(wǎng)絡(luò)請(qǐng)求庫,目前Fly.js支持的平臺(tái)包括:Node.js 、微信小程序 、Weex 、React Native 、Quick App 和瀏覽器。
也就是說在以上的平臺(tái)中,我們可以用flyio直接發(fā)起http請(qǐng)求,而且在代碼中的表現(xiàn)是統(tǒng)一的的。
安裝依賴
cnpm i -S flyio
使用
創(chuàng)建request工具類,初始化Flyio對(duì)象
function createFly() {
if (mpvuePlatform === 'wx') {
const Fly = require('flyio/dist/npm/wx')
return new Fly()
} else if (mpvuePlatform === 'my') {
const Fly = require('flyio/dist/npm/ap')
return new Fly()
} else {
return null
}
}
處理get請(qǐng)求
export function get(url, params = {}) {
const fly = createFly()
if (fly) {
return new Promise((resolve, reject) => {
fly.get(url, params).then(response => {
console.log(response)
resolve(response)
}).catch(err => {
console.log(err)
handleError(err)
reject(err)
})
})
}
}
處理post請(qǐng)求
export function post(url, params = {}) {
const fly = createFly()
if (fly) {
return new Promise((resolve, reject) => {
fly.post(url, params).then(response => {
console.log(response)
resolve(response)
}).catch(err => {
console.log(err)
handleError(err)
reject(err)
})
})
}
}
在頁面中的使用
<template>
<div>
<div class="text">
ibook
</div>
<van-button type="primary" @click="jump">按鈕</van-button>
</div>
</template>
<script>
import {get} from '@/utils/request'
export default {
methods:{
jump(){
// this.$router.push('/pages/index/main')
get('https://www.baidu.com').then(res =>{
console.log(res)
})
}
}
}
</script>
<style lang="scss" scoped>
.text{
color: red;
}
</style>
在微信開發(fā)者工具中的運(yùn)行結(jié)果

image.png
至此,flyio庫就集成完畢了。