1,在根目录utils下创建一个index.js文件,用来写封装的request
2,创建config/index.js来放我们的基础路径
3,utils/index.js
import {BASEURL} from '../config/index';//引入基础路径 export function $get(url,success){ $request(url,'GET',success) } export function $post(url,success){ $request(url,'POST',success) } function $request(url,methods,success){ wx.showLoading({ title: '加载中...', }) wx.request({ methods, url: BASEURL+url, success:res=>{ success(res.data); }, complete(){ wx.hideLoading({ success: (res) => {}, }) } }) }4,页面调用:
import{$get} from '../../utils/index'; Page({ /** * 页面的初始数据 */ data: { menulist:[] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { $get('/menulist',({menulist})=>{ this.setData({ menulist }) }) }, })用promise,async封装request,可以使用更加方便,优化请求
utils/index.js
import { BASEURL } from '../config/index'; export function $get(url) { return $request(url, 'GET') } export function $post(url) { return $request(url, 'POST') } function $request(url, methods) { wx.showLoading({ title: '加载中...', }) return new Promise((resolve,reject)=>{ wx.request({ methods, url: BASEURL + url, success: res => { resolve(res.data); }, fail(e){ reject(e); }, complete() { wx.hideLoading({ // success: (res) => {}, }) } }) }) }页面调用:
import{$get} from '../../utils/index'; Page({ /** * 页面的初始数据 */ data: { menulist:[] }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.getMenulist(); }, async getMenulist(){ let {menulist}=await $get('/menulist') this.setData({ menulist }) }, })这样写也是可以的:
/** * 生命周期函数--监听页面加载 */ onLoad: function (options) { let pro=$get('/menulist') console.log(pro) pro.then(({menulist})=>{ this.setData({ menulist }) }) },其中出现一个问题,不过只要把下面增强编译勾上就可以了 ,