目錄結構
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(); } })
注意:引入變量或類時,都需要使用相對路徑,否則找不到文件報錯。