導語
上一篇文章微信小程序搭建mpvue+vant已經介紹了如何搭起mpvue項目及引入vant,本篇文章繼續在它的基礎上,引入flyio,並做一些封裝,目的是為了在小程序發起請求。
這時讀者會有些疑問,小程序已經有了request,為什么還用flyio?這不是造輪子嗎?我是這么想的,其實現在不管是mpvue,還是wepy都好像還不能完美編譯出微信小程序和h5版本。為了以后應對老板有創建h5版本的想法,我們應該為以后復用小程序代碼做好准備工作。既然h5也會有ajax,flyio也支持小程序和h5的,所以干脆把flyio引進來,再做一些封裝,兩邊都能用,豈不美哉?
文章末尾,附文章教程步驟創建的項目mpvue+vant+flyio,需要學習的同學,拿走不謝。
第一步:將flyio加入項目
我的項目路徑:/Users/hrz/myworkspace/lawyer-card-wxss
$ cd /Users/hrz/myworkspace/lawyer-card-wxss $ cnpm i flyio -S --production
正確姿勢
第二步:二次封裝
創建api文件夾,並在下面新建兩個文件api.js,httpRequest.js
正確姿勢
api.js 用來給各頁面調用,是一個匯總各類ajax方法的集合
import requestService from './httpRequest' const PROD_SERVICE = 'https://我的線上產品域名/lawyer-card-service' const DEV_SERVICE = 'http://localhost:8081/lawyer-card-service' /** * 根據開發環境返回接口url * @returns {string} */ function getSerive () { if (process.env.NODE_ENV === 'production') { return PROD_SERVICE } else { return DEV_SERVICE } } /** wx.request服務封裝 */ export default { /** * 檢查微信Token是否還生效 * @param data * @param callBack */ checkToken (data, callBack, failCallBack) { requestService.sendRequest().url(getSerive() + '/auth/checkToken').method('GET').data(data).success(res => { callBack(res) }).fail(res => { failCallBack(res) }).send() } }
httpRequest.js是對flyio對二次封裝,是ajax的核心
import {getStorageSync, hideLoading, showLoading, showNotify} from '../utils/index' var Fly = require('flyio/dist/npm/wx') var fly = new Fly() // 設置超時 fly.config.timeout = 7000 // 添加請求攔截器 fly.interceptors.request.use((request) => { // 給所有請求添加自定義header const token = getStorageSync('token') request.headers['token'] = token return request }) /** * request服務封裝 */ export default { sendRequest } function sendRequest () { return { _sucCallback: null, _failCallback: null, _method: 'GET', _data: {}, _header: {'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'}, _url: '', send: function () { showLoading({ title: '加載中...' }) fly.request(this._url, this._data, { method: this._method, headers: this._header }) .then(res => { hideLoading() let error = httpHandlerError(res, this._failCallback) if (error) return this._sucCallback(res) }) .catch((res) => { hideLoading() httpHandlerError(res, this._failCallback) }) return this }, success: function (callback) { this._sucCallback = callback return this }, fail: function (callback) { this._failCallback = callback return this }, url: function (url) { this._url = url return this }, data: function (data) { this._data = data return this }, method: function (method) { this._method = method return this }, header: function (header) { this._header = header return this } } } /** * info 請求完成后返回信息 * callBack 回調函數 * errTip 自定義錯誤信息 */ function httpHandlerError (info, callBack) { hideLoading() /** 請求成功,退出該函數 可以根據項目需求來判斷是否請求成功。這里判斷的是status為200的時候是成功 */ let haveError = true let errTip if (info.status === 200) { if (info.data.code === undefined) { haveError = true } else if (info.data.code === 'success' || info.data.code === 0) { haveError = false } else { haveError = true errTip = info.data.msg } } else { errTip = '網絡請求出現了錯誤【' + info.status + '】' haveError = true } if (haveError) { /** 發生錯誤信息時,如果有回調函數,則執行回調 */ if (callBack) { callBack(info) } else { showNotify(errTip) } } return haveError }
大家看到,httpRequest.js里引用一些工具類,其實里面主要是一些加載的提示,及彈框。為什么我要把他放在工具類里?正如我最開頭導語說的,為了方便以后應對h5版本,H5版本的加載、彈框、操作緩存和小程序的代碼不一樣,所以我統一放在工具類里管理了,以后要做h5開發,我只要改工具類就行了。下面是小程序里工具類的代碼。
import Notify from 'vant-weapp/dist/notify/notify' /** * 顯示頂部紅色通知 * 使用方法:調用時確保界面上有: * <van-notify id="van-notify"/> * @param msg * @param showTime */ export function showNotify (msg, showTime) { if (!showTime) { showTime = 3000 } Notify({ text: msg, duration: showTime }) } /** * 從緩存里獲取數據 * @param key * @return value */ export function getStorageSync (key) { return wx.getStorageSync(key) } /** * 顯示加載中 * @param data */ export function showLoading (data) { wx.showLoading(data) } /** * 隱藏加載中 */ export function hideLoading () { wx.hideLoading() } /** * 將數據保存到緩存 * @param key * @param value */ export function setStorageSync (key, value) { wx.setStorageSync(key, value) } export default { getStorageSync, setStorageSync, showLoading, hideLoading, showNotify }
第三步:寫個Demo發送請求
<template> <div> {{msg}} </div> </template> <script> import Api from '../../apis/api' export default { data () { return { msg: null } }, methods: {}, onLoad () { let that = this let token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxIiwiaWF0IjoxNTU0MjA0NDI0LCJleHAiOjE1NTQ4MDkyMjR9.VdlhGXOxIA97_G_u_a3GJxmWdD9t_jb_a1aodTJ75ESNgxchx8M0mRBSx-s_er8Da4MzZY1zBW4UfY5ELC9fgA' Api.checkToken({'token': token}, function (res) { console.log(res) that.msg = res.data.msg }) } } </script> <style scoped> </style>
正確姿勢
運行npm run dev起來,去小程序開發工具看效果
正確姿勢
已經成功發送請求,還是不錯的!
我創建了名字為mpvue-vant-flyio項目,除了項目名稱不同,步驟都是相同的。項目源碼
轉載鏈接:https://www.jianshu.com/p/b308a89f8180