美团出品的mpvue已经开源出来好久了,一直说要进行一次实践,这不最近一次我的小程序开发就用上了它。html
看了微信官方的数据请求模块--request,对比了下get和post请求的代码,发现若是在每个地方都用request的话,那会有不少代码是冗余的,因而就准备本身封装一个,下面就记录一下封装过程。注释也写在下面的代码里了。vue
//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;//暴露出来供其余文件引用
// src/main.js import Vue from 'vue'; import App from '@/App'; import MpvueRouterPatch from 'mpvue-router-patch'; import net from '@/utils/net';//导入封装好的net import 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 }
// src/pages/home/index.vue <template> <!--省略coding--> </template> <script> export default { data() { return {} bannerList:[], navList:[], newsitems:[], about:"", applay:false, } }, onLoad () { this.getData(); }, methods:{ async getData(){ //注意方法名以前必定要加上异步async this.bannerList=[]; let bannerList = await this.$net.get(this.$apis.bannerList,{}); let newsitems = await this.$net.get(this.$apis.article,{});//请求数据前面要加上await,是与async配套使用 let aboutus = await this.$net.get(this.$apis.aboutus,{}); let isApplay = await this.$net.get(this.$apis.datadict+'/kMiCYYYg',{}); // console.log(isApplay); if(isApplay.remark1=='1'){ this.applay = true; } this.newsitems = newsitems.results; // this.bannerList = bannerList.results; bannerList.results.forEach(el => { if(el.is_open==1){ this.bannerList.push(el); } }); this.about = aboutus.results[1].desc; // console.log(aboutus) }, } </script> <style> /* 省略样式coding **/ </style>
此次对微信数据请求的封装过程当中学习了一下Promise,使得代码更简洁了。踩了一些坑:好比说async必定要与await配套使用,数据请求前要加上异步async。git
这里贴一下Promise的技术贴以留后用:es6