WeChat-微信小程序-引入类model

import {
  Home
} from './home-model.js';
var home = new Home();



// 获取产品列表
      home.getProductList((res) => {
        this.setData({
          product_list: res.data.data
        })
      })



import {
  Base
} from '../../utils/base.js';
var base = new Base();
class Home {
  constructor() {

  }

  // 获取banner轮播图
  getBannerList(callBack) {
    // console.log('2.----进入到home-model模型mvc中')
    var params = {
      url: '/banner_all',
      callBack: callBack
    }
    base.request(params);
  }
  // 获取所有产品列表
  getProductList(callBack) {
    var params = {
      url: '/product_all',
      callBack:callBack
    }
    base.request(params);
  }

  getDemo(){
    console.log('demo')
  }
}
export {
  Home
}


import {Home} from './home-model.js';

var home = new Home()
Page({

  /**
   * 页面的初始数据
   */
  data: {

  },

  onLoad: function() {
    this._onLoad();
  },
  _onLoad: function() {
    var data = home.getBannerList();
  },

})
home-model.js

class Home{
  constructor(){

  }
  getBannerList(){
    wx.request({
      url: 'https://api.myphp.vip/userapi/v1/banner_all',
      method:'get',
      success:function(res){
        console.log(res)
      }
    })
  }
}

export {Home}

==============================================================================
路径:utils/base.js

import { Config } from '../utils/config.js';
class Base {
  constructor() {
    // this.baseRequestUrl = 'https://api.myphp.vip/userapi/v1';
    this.baseRequestUrl = Config.restUrl;
  }

  request(params) {
    var url = this.baseRequestUrl + params.url;
    console.log(url);
    // 传参方式默认GET方式
    if (params.type) {
      params.method = 'GET';
    }

    // 发送网络请求
    wx.request({
      url: url,
      method: params.type,
      header: {
        'content-type': 'application/json',
        'token': 1
      },
      success: function(res) {
        console.log('success进入到base.js中');
        if (params.callBack) {
          params.callBack(res.data);
        } else {
          return res.data;
        }

      },
      fail: function(err) {
        console.log('进入到base,js中======error');
      }
    })
  }
}
export {
  Base
};

路径:utils/config.js

class Config {
  constructor() {

  }
 
}
Config.restUrl = 'https://api.myphp.vip/userapi/v1';

export {
  Config
};

你可能感兴趣的:(WeChat)