小程序技术栈整合

330 阅读2分钟

一、 mpvue配置

  1. 全局安装 vue-cli

    npm install --global vue-cli@2.9.6        
    npm install @vue/cli-init -g 
    
  2. 创建一个基于 mpvue-quickstart 模板的新项目

    新手一路回车选择默认就可以了

    vue init mpvue/mpvue-quickstart my-project
    

二、 mpvue中配置 vant-weapp

  1. 下载 vant-weapp 资源

    git clone https://github.com/youzan/vant-weapp.git
    
  2. 将dist目录下的所有文件复制到你项目的/static/vant/目录下

注意打开 微信开发者工具中的ES6转ES5功能

  1. 在需要引入的页面目录下的main.json文件中

    {      
        "usingComponents": {        
            "van-button": "/static/vant/button/index",      
        }    
    }
    
  2. 使用

    <van-button>测试</van-button>
    

三、 mpvue中配置 flyio

  1. 安装 flyio

    yarn add flyio -S  
    
  2. 新建文件 src/api/fly.js

    import Fly from 'flyio/dist/npm/wx'
    const fly = new Fly()
    const host = 'http://127.0.0.1:5000/' // 添加请求拦截器
    fly.interceptors.request.use((request) => {
    wx.showLoading({
    title: '加载中',
    mask: true
    })
    console.log(request)
    // request.headers["X-Tag"] = "flyio";
    // request.headers['content-type']= 'application/json';
    request.headers = {
    'X-Tag': 'flyio',
    'content-type': 'application/json'
    }​
    let authParams = { // 公共参数
    'categoryType': 'SaleGoodsType@sim',
    'streamNo': 'wxapp153570682909641893',
    'reqSource': 'MALL_H5',
    'appid': 'string',
    'timestamp': new Date().getTime(),
    'sign': 'string'
    }​
    request.body && Object.keys(request.body).forEach((val) => {
    if (request.body[val] === '') {
    delete request.body[val]
    };
    })
    request.body = {
    ...request.body,
    ...authParams
    }
    return request
    }) // 添加响应拦截器
    fly.interceptors.response.use((response) => {
    wx.hideLoading()
    return response.data// 请求成功之后将返回值返回
    },
    (err) => {
    // 请求出错,根据返回状态码判断出错原因
    console.log(err)
    wx.hideLoading()
    if (err) {
    return '请求失败'
    };
    })
    fly.config.baseURL = host
    export default fly

  3. 将fly.js引入main.js然后直接挂载到vue原型上

    import fly from './api/fly'    
    Vue.prototype.$fly = fly
    

四、使用Promise封装小程序网络请求

// 1\. 基于Promise的网络请求库, 包含GET POST请求
// 2.使用方法:
//   1).先引入: import { get, post,... } from 本文件;
//   2).get请求: get("/index", { id: 2 }).then(data => { }).catch(error => { });
//   3). post请求: post("/index", { id: 2 }).then(data => { }).catch(error => { });

/* 服务器请求地址 */
export const domain = 'http://203.195.181.208:8888/';
/**
* 发起get请求
* @param url 请求路径 必填
* @param data 请求参数 get请求的参数会自动拼到地址后面
* @param headers 请求头 选填
* @returns {Promise}
*/
export const get = (url, data, headers) => request('GET', url, data, headers);

/**
* 发起post请求
* @param url 请求路径 必填
* @param data 请求参数
* @param headers 请求头 选填
* @returns {Promise}
*/
export const post = (url, data, headers) => request('POST', url, data, headers);

/**
* 接口请求基类方法
* @param method 请求方法 必填
* @param url 请求路径 必填
* @param data 请求参数
* @param header 请求头 选填
* @returns {Promise}
*/
export function request(method, url, data, header = {
  'Content-Type': 'application/json'
}) {
  // 请求之前提示加载中
  wx.showLoading({
    title: '加载中...'
  });
  return new Promise((resolve, reject) => {
    const response = {};
    url = domain + url;
    wx.request({
      url,
      method,
      data,
      header,
      success: (res) => response.success = res,
      fail: (error) => response.fail = error,
      complete() {
        wx.hideLoading();
        if (response.success) {
          if (response.success.statusCode != 200) {
            wx.showToast({
              title: "网络出错,稍后再试",
              icon: "none"
            });
            return;
          }
          resolve(response.success.data);
        } else {
          wx.showToast({
            title: "数据请求失败,请稍后重试",
            icon: "none"
          });
          console.log('数据请求失败', response.fail)
          reject(response.fail);
        }
      },
    });
  });
}