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

20180531152773555924152.png

简介

美团出品的mpvue已经开源出来很久了,一直说要进行一次实践,这不最近一次个人小程序开发就用上了它。

看了微信官方的数据请求模块--request,对比了下get和post请求的代码,发现如果在每一个地方都用request的话,那会有很多代码是冗余的,于是就准备自己封装一个,下面就记录一下封装过程。注释也写在下面的代码里了。

实现的结果

  • 代码要简洁

  • 无需每个页面引入一次

  • Promise化,避免回调地狱

封装代码

 1//src/utils/net.js
2import wx from 'wx';//引用微信小程序wx对象
3import { bmobConfig } from '../config/bmob';//bmob配置文件
4const net = {
5  get(url, data) {
6    wx.showLoading({
7      title: '加载中',//数据请求前loading,提高用户体验
8    })
9    return new Promise((resolve, reject) => {
10      wx.request({
11        url: url,
12        data: data,
13        method: 'GET', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
14        header: {
15          'X-Bmob-Application-Id': bmobConfig.applicationId,
16          'X-Bmob-REST-API-Key': bmobConfig.restApiKey,
17          'Content-Type': 'application/json'
18        }, // 设置请求的 header
19        success: function (res) {
20          // success
21          wx.hideLoading();
22          if(res.statusCode!=200){
23            wx.showToast({
24              title: "网络出错,稍后再试",
25              icon: "none"
26            });
27            return false;
28          }
29          resolve(res.data);
30        },
31        fail: function (error) {
32          // fail
33          wx.hideLoading();
34          reject(error);//请求失败
35        },
36        complete: function () {
37          wx.hideLoading();
38          // complete
39        }
40      })
41    })
42  },
43  post(url, data) {
44    wx.showLoading({
45      title: '加载中',
46    })
47    return new Promise((resolve, reject) => {
48      wx.request({
49        url: url,
50        data: data,
51        method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
52        header: {
53          'X-Bmob-Application-Id': bmobConfig.applicationId,
54          'X-Bmob-REST-API-Key': bmobConfig.restApiKey,
55          'Content-Type': 'application/json'
56        }, // 设置请求的 header
57        success: function (res) {
58          // success
59          wx.hideLoading();
60          resolve(res.data);
61        },
62        fail: function (error) {
63          // fail
64          wx.hideLoading();
65          reject(error);
66        },
67        complete: function () {
68          // complete
69          wx.hideLoading();
70        }
71      })
72    })
73  }
74}
75export default net;//暴露出来供其他文件引用

使用方法

  • 全局配置请求方式,避免每次import

 1// src/main.js
2import Vue from 'vue';
3import App from '@/App';
4import MpvueRouterPatch from 'mpvue-router-patch';
5import net from '@/utils/net';//导入封装好的net
6import shareConfig from '@/config/share';
7Vue.prototype.$net=net;//微信小程序网络请求的配置
8Vue.config.productionTip = false
9Vue.use(MpvueRouterPatch)
10const app = new Vue({
11  ...App
12})
13app.$mount()
14export default {
15  //省略coding
16}
  • 发送请求实例,第一步已经全局配置了net,使用时直接用this.$net即可使用net的方法(get/post)

 1// src/pages/home/index.vue
2<template>
3<!--省略coding-->
4</template>
5<script>
6export default {
7data() {
8    return {}
9      bannerList:[],
10      navList:[],
11      newsitems:[],
12      about:"",
13      applay:false,
14    }
15},
16onLoad () {
17    this.getData();
18},
19methods:{
20    async getData(){
21    //注意方法名之前一定要加上异步async
22      this.bannerList=[];
23      let bannerList = await this.$net.get(this.$apis.bannerList,{});
24      let newsitems = await this.$net.get(this.$apis.article,{});//请求数据前面要加上await,是与async配套使用
25      let aboutus = await this.$net.get(this.$apis.aboutus,{});
26      let isApplay = await this.$net.get(this.$apis.datadict+'/kMiCYYYg',{});
27      // console.log(isApplay);
28      if(isApplay.remark1=='1'){
29        this.applay = true;
30      }
31      this.newsitems = newsitems.results;
32      // this.bannerList = bannerList.results;
33      bannerList.results.forEach(el => {
34        if(el.is_open==1){
35          this.bannerList.push(el);
36        }
37      });
38      this.about = aboutus.results[1].desc;
39      // console.log(aboutus)
40    },
41}
42</script>
43<style>
44/*
45省略样式coding
46**/
47</style>

总结

这次对微信数据请求的封装过程中学习了一下Promise,使得代码更简洁了。踩了一些坑:比如说async一定要与await配套使用,数据请求前要加上异步async。

 

 转载自:https://mp.weixin.qq.com/s/3VbmA2qOS4tS0JgBR0Lyqg

 
 
posted @ 2018-07-11 10:10  heroljy  阅读(1573)  评论(0编辑  收藏  举报