vuex与axios网络请求解耦

283 阅读2分钟

axios.png

背景简介

项目开发中,vuex与网络请求经常是耦合的。需要使用网络请求时,通常要引用网络接口文件,再调用里面的方法。这样导致代码耦合度太高,维护成本高。

解耦思路

解耦思路,将网络请求单独封装成一个文件。vuex里,单独封装到一个modules里,网络请求封装成actions方法。在需要使用网络请求的地方,通过vuex发送dispatch,实现网络请求的解耦。这样维护成本低,代码可读性高。

前提

安装axios

npm install axios --save

具体实现

  1. 创建一个plugin文件夹,里面创建一个http.ts文件,用于统一管理网络请求。这里只实现了get方法,其他方法类似。
let xToken = "";
//设置token
export function setToken(mToken: string) {
  xToken = mToken;
}
//http请求拦截
instance.interceptors.request.use(
  (config: any) => {
    //业务处理
    return config;
  },
  (err:any) => {
    return Promise.reject(err);
  }
);
//响应拦截
instance.interceptors.response.use(
  (res: AxiosResponse) => {
    //业务处理
    return res.data;
  },
  (err:any) => {
    return Promise.reject(err);
  }
);
//get请求封装
export function get(url: string, params = {}) {
  return new Promise((resolve, reject) => {
    instance
      .get(url, {
        params: params,
        paramsSerializer: params => {
          return qs.stringify(params, { indices: false, skipNulls: true });
        }
      })
      .then(response => {
        resolve(response);
      })
      .catch(err => {
        reject(err);
      });
  });
}

  1. 单独封装一个vuex module文件,用于响应处理网络请求的dispatch。httpstore_data.ts 里的actions如下
import { get, setToken } from "@/plugin/http";
const actions = {
  //设置token
  setTokenAction(cont: any, param: any) {
    setToken(param.token);
  },
  //get请求Action
  axiosGetAction(cont: any, param: any) {
    const mUrl = param.url;
    const mParam = param.param;
    return new Promise((resolve, reject) => {
      get(mUrl, mParam).then((res: any) => {
        if (res) {
          resolve(res);
        } else {
          reject(res);
        }
      });
    });
  }
};
export default {
  namespaced: true,
  mutations
};
  1. 在需要用到网络请求时,我们只需要派发vuex的dispatch即可。实现了解耦。如我们在demo_data.ts里的调用。
const actions = {
  ……
  getDemoData({ dispatch }: any, param: any) {
    const mObj = {
      param: param,
      url:
        "http://47.103.114.48:8002/open/manage/common/region"
    };
    return new Promise((resolve, reject) => {
      // 派发vuex的dispatch,实现网络请求的解耦。
      dispatch("httpstore/axiosGetAction", mObj, { root: true }).then(
        (res: any) => {
          if (res.code === 200) {
            resolve(res.data);
          } else {
            reject(res.msg);
          }
        }
      );
    });
  }
};

源码下载:https://gitee.com/leolee18/vue3-project

系列文档

vue3 两种创建方式详解(cli和vite)
vue.config.js/vite.config…
vue3 自动引入自定义组件
vueX vue3自动引入匹配的modules
vue3 自定义指令控制按钮权限的操作
vuex与axios网络请求解耦
移动端rem适配布局