mpvue学习笔记-之微信小程序数据请求封装

20180531152773555924152.png 简介 美团出品的mpvue已经开源出来很久了,一直说要进行一次实践,这不最近一次个人小程序开发就用上了它。
看了微信官方的数据请求模块--request,对比了下get和post请求的代码,发现如果在每一个地方都用request的话,那会有很多代码是冗余的,于是就准备自己封装一个,下面就记录一下封装过程。注释也写在下面的代码里了。
实现的结果

  • 代码要简洁
  • 无需每个页面引入一次
  • Promise化,避免回调地狱
封装代码
//src/utils/net.js import wx from 'wx'; //引用微信小程序wx对象 import { bmobConfig } from '../config/bmob'; //bmob配置文件const net = { get(url, data) { wx.showLoading({ title: '加载中',//数据请求前loading,提高用户体验 }) return new Promise((resolve, reject) => { wx.request({ url: url, data: data, method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT header: { 'X-Bmob-Application-Id': bmobConfig.applicationId, 'X-Bmob-REST-API-Key': bmobConfig.restApiKey, 'Content-Type': 'application/json' }, // 设置请求的 header success: function (res) { // success wx.hideLoading(); if(res.statusCode!=200){ wx.showToast({ title: "网络出错,稍后再试", icon: "none" }); return false; } resolve(res.data); }, fail: function (error) { // fail wx.hideLoading(); reject(error); //请求失败 }, complete: function () { wx.hideLoading(); // complete } }) }) }, post(url, data) { wx.showLoading({ title: '加载中', }) return new Promise((resolve, reject) => { wx.request({ url: url, data: data, method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT header: { 'X-Bmob-Application-Id': bmobConfig.applicationId, 'X-Bmob-REST-API-Key': bmobConfig.restApiKey, 'Content-Type': 'application/json' }, // 设置请求的 header success: function (res) { // success wx.hideLoading(); resolve(res.data); }, fail: function (error) { // fail wx.hideLoading(); reject(error); }, complete: function () { // complete wx.hideLoading(); } }) }) } }export default net; //暴露出来供其他文件引用

使用方法
  • 全局配置请求方式,避免每次import
// src/main.js import Vue from 'vue'; import App from '@/App'; import MpvueRouterPatch from 'mpvue-router-patch'; import net from '@/utils/net'; //导入封装好的netimport shareConfig from '@/config/share'; Vue.prototype.$net=net; //微信小程序网络请求的配置Vue.config.productionTip = false Vue.use(MpvueRouterPatch)const app = new Vue({ ...App }) app.$mount()export default { //省略coding }

  • 发送请求实例,第一步已经全局配置了net,使用时直接用this.$net即可使用net的方法(get/post)
// src/pages/home/index.vue /* 省略样式coding **/

总结 这次对微信数据请求的封装过程中学习了一下Promise,使得代码更简洁了。踩了一些坑:比如说async一定要与await配套使用,数据请求前要加上异步async。
【mpvue学习笔记-之微信小程序数据请求封装】这里贴一下Promise的技术贴以留后用:
  • 大白话讲解Promise
  • 阮一峰ES6-Promise对象

    推荐阅读