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

 
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM