簡介
美團出品的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';//導入封裝好的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
}
- 發送請求實例,第一步已經全局配置了net,使用時直接用this.$net即可使用net的方法(get/post)
// 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。
這里貼一下Promise的技術貼以留后用: