mpvue項(xiàng)目集成flyio網(wǎng)絡(luò)請(qǐng)求庫

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庫就集成完畢了。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容