Applet micro-channel structures mpvue + vant + flyio

Lead

An article on the micro-channel program to build small mpvue + vant 've covered how to set up mpvue project and introduced vant, this article continues on the basis of it, the introduction of flyio, and do some package aimed at small program to initiate the request.

Then readers will have some questions, applets have request, why use flyio? It's not create the wheel it? I think so, in fact, whether it is mpvue, or wepy seemed not to compile a perfect micro-channel version applets and h5. In order to cope with future versions of the bosses have created h5 idea, we should be well prepared for future reuse applet code. Since the h5 will have ajax, flyio also supports applets and h5, so just put flyio bringing in, do some package, both sides can be used, not Miya?

End of the article, the article attached to the project mpvue step tutorials created + vant + flyio, students need to learn, do not mention it away.

The first step: join the project flyio

My project path: / Users / hrz / myworkspace / lawyer-card-wxss

$ cd /Users/hrz/myworkspace/lawyer-card-wxss
$ cnpm i flyio -S --production 
 
Correct posture

Step Two: Secondary Packaging

Creating api folder and create two files in the following api.js , httpRequest.js

 
Correct posture

api.js used to call each page is a summary of the method of collection of all kinds of 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 is flyio secondary package, the core of 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 } 

We can see, httpRequest.js in reference to some of the tools, in fact, there are some major tips loaded and bomb box. Why do I want him on the tool class? As I said at the beginning of most introductions, in order to facilitate future deal with h5 version, H5 version of the add, playing box, operation code caching and applet is not the same, so I put a unified management tools in the future to do h5 development, I just changed tools on the line. The following is a small program in the utility class code.

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 } 

The third step: sending a request to write a 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> 
 
Correct posture

运行npm run dev起来,去小程序开发工具看效果

 
正确姿势

已经成功发送请求,还是不错的!

我创建了名字为mpvue-vant-flyio项目,除了项目名称不同,步骤都是相同的。项目源码



转载链接:https://www.jianshu.com/p/b308a89f8180

Guess you like

Origin www.cnblogs.com/blogsaspx/p/11291406.html