多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[TOC] ### 1. config 定义url ~~~ const config ={ base_url_api:"https://douban.uieee.com/v2/movie/" } export {config}; ~~~ ### 2. 封装http ~~~ import { config } from "../config"; class HTTP { request({url,method="GET",data={}}) { const promise = new Promise((resolve, reject) => { wx.request({ url: config.base_url_api + url, data, method, header: { 'Content-Type': 'json', }, success: res=> { const statusCode = res.statusCode.toString(); if (statusCode.startsWith("2")) { resolve(res.data); } else { this._show_error(); } }, fail: err=> { reject(err); this._show_error(); } }) }) return promise; } _show_error() { wx.showToast({ title: '网络错误', icon: 'none' }) } } export { HTTP }; ~~~ ### 3. 再次封装 ~~~ import {HTTP} from "../utils/http-p"; class MovieModel extends HTTP{ getInTheaters(){ return this.request({ url:"in_theaters" }) } getTop250(){ return this.request({ url:"top250" }) } getComingSoon(){ return this.request({ url:"coming_soon" }) } } export {MovieModel}; ~~~ ### 4. 使用 ~~~ //index.js //获取应用实例 import {MovieModel} from "../../models/movie-p"; const movieModel = new MovieModel(); Page({ onLoad(){ const inTheaters = movieModel.getInTheaters() const top250 = movieModel.getTop250(); const comingSoon = movieModel.getComingSoon(); Promise.all([inTheaters,top250,comingSoon]).then(res=>{ let [inTheaters,top250,comingSoon] = res; console.log(inTheaters); console.log(top250); console.log(comingSoon); }) } }) ~~~