Unified management of API and data separation in mpvue project

My GitHub blog, a lot of content can be seen, like the stars https://github.com/liangfengbo/frontend

Unified management of API and data separation in mpvue project

The wx: request is used for the request data interface in the applet, because it is considered that the project is relatively large, it is best to encapsulate wx: request and use management in a unified way

utils.js configuration development environment and online environment interface

let util = {};

const ajaxUrl = process.env.NODE_ENV === 'development'
  // 测试接口地址
  ? 'code.net.cn/api'
  // 线上接口地址
  : 'https://api.code.net.cn';


util.API = ajaxUrl;
util.oauthUrl = ajaxUrl;

export default util;

fetch.js exposes the package request interface

import utils from '../utils/utils'
import store from '../vuex/index'

export async function request(obj) {

  let token = store.state.wechat.token;

  return new Promise((resolve, reject) => {
    // 是否显示loading
    if (obj.dontLoading !== true) {
      wx.showNavigationBarLoading();
      wx.showLoading({
        mask: true,
        title: '处理中'
      });
    }

    wx.request({
      url: utils.API + obj.url,
      data: obj.data,
      header: {
        'content-type': 'application/json',
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + token,
        ...obj.header
      },
      method: obj.method,

      success(res) {

        // 处理返回信息
        handleResult(res);

        // 处理 new token
        handleNewToken(res);

        if (obj.dontLoading !== true && store.state.showing !== true) {
          wx.hideLoading();
          wx.hideNavigationBarLoading();
        }

        store.commit('setShowing', false);

        resolve(res.data.data)
      },

      fail(e) {

        reject(e)
      }

    })
  })
}

// 处理new token
function handleNewToken(res) {
  let new_token = res.header['New-Token'];
  if (new_token) {
    store.commit('setToken', new_token)
  }
}

// 统一显示toast
function showToast(message) {
  wx.showToast({
    title: message,
    icon: 'none',
    duration: 2000
  });

  store.commit('setShowing', true);
}
/**
 * 处理code信息
 * @param res
 */
function handleResult(res) {

  let code = res.data.code;
  switch (code) {
    case 200:
      break;
    case 401 :
      showToast("身份校验信息失败,请刷新页面重试!");
      store.dispatch('getUserToken');
      break;

    case 412 :
      showToast('未填写个人信息!');
      wx.navigateTo({url: '../bind/main'});
      break;

    case 422 :
      let errors = '';
      for (var key in res.data.errors) {
        res.data.errors[key].forEach((item) => {
          errors += item + " "
        })
      }
      errors = errors ? errors : '提交的信息错误,请检查!';
      showToast(errors);
      break;

    default:
      let msg = res.data.message ? res.data.message : '未知错误,请重试!';
      showToast(msg);
  }
}

Unified data request interface in vuex

For example, order interface

import {request} from "../../api/fetch";

const state = {
  // 订单列表
  orderList: [],
}

const mutations = {
  setOrderList(state, data) {
    state.orderList = data;
  }
}

const actions = {
  /**
   * 下订单
   * @param commit
   * @param params
   * @returns {Promise<*>}
   */
  async createOrder({commit}, params) {
    const res = await request({
      method: 'post',
      url: '/wechat/order',
      data: params,
    });
    return res;
  },

  /**
   * 获取订单详情
   * @param commit
   * @param id 订单id
   * @returns {Promise<*>}
   */
  async getOrderDetail({commit}, id) {
    const res = await request({
      method: 'get',
      url: '/wechat/order/' + id,
      data: {}
    })
    return res;
  },

  /**
   * 获取订单列表
   * @param commit
   * @returns {Promise<*>}
   */
  async getOrderList({commit}) {
    const res = await request({
      method: 'get',
      url: '/wechat/order',
      data: {}
    })
    commit('setOrderList', res);
    return res;
  }
}

export default {
  state,
  actions,
  mutations
}

Now that the interface API and the request data are processed separately, the data can be used only by calling on the page

<script>
  import {mapActions, mapState} from 'vuex';

  export default {

    computed: {
      ...mapState({
        orderList: state => state.order.orderList,
      }),

    },
    async onShow() {
    
      // 调用请求获取订单列表接口
      await this.getOrderList();
    },
    methods: {
      ...mapActions([
        'getOrderList',
      ]),
    }
  }

</script>

Let me talk a little bit here. Async / await and Promise are asynchronous. My project uses both promise and async / await. The two have different advantages and disadvantages. The callback mechanism of Promise is async / await. Callback, async / await is written very similar to synchronous writing, and the code is neat and easy to understand. Than recommend everyone to use them in different scenarios.

Guess you like

Origin www.cnblogs.com/homehtml/p/12715256.html