小程序定义并使用类

目录结构

config.js

const myShowLoading = (info,time)=>{
  wx.showLoading({
    title: info,
  });
  setTimeout(function(){
    wx.hideLoading();
  },time)
}
const baseUrl = 'https://www.topmy.cn/api'
//暴露定义的变量
module.exports = { myShowLoading: myShowLoading, baseUrl: baseUrl }

http.js

let config = require('config.js')//引入变量
//定义http类
class HTTP{
 request(params){
   wx.request({
     url: config.baseUrl + params.url,//使用变量
     data: params.data,
     header: {},
     method: params.method || 'GET',
     dataType: 'json',
     responseType: 'text',
     success: (res)=> {
       let code = res.data.status;
        if(code == 1){
          params.success(res);
        }else{
          console.log(res.data.message);
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 2000
          })
        }
     },
     fail: function (res) { },
     complete: function (res) { },
   })
 }
}
//暴露定义的类
export {
  HTTP
}

index.js

import {HTTP} from '../../utils/http.js';//引入定义的类
let http = new HTTP();//实例化类
Page({
  /**
   * 页面的初始数据
   */
  data: {
    caseType: []
  },
  //案例列表
  getCaseType: function (){
//使用定义的类 http.request({ url:
'/get_category_type', data: { "position_id": 2 }, method: 'POST', success: (res)=>{ console.log(res.data); this.setData({ caseType: res.data.data }) } }) }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { this.getCaseType(); } })

 注意:引入变量或类时,都需要使用相对路径,否则找不到文件报错。

原文地址:https://www.cnblogs.com/duanzhenzhen/p/11248449.html