小程序定義並使用類


目錄結構

 

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(); } })

 

 注意:引入變量或類時,都需要使用相對路徑,否則找不到文件報錯。


免責聲明!

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



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