zoukankan      html  css  js  c++  java
  • ⑦ vue项目结构study

    1 src目录结构

    2 main.js -- 引入全局样式文件+全局路由钩子配置文件

    3 utils配置文件 -- request.js 封装 axios 请求函数

    3.1 使用 interceptors 配置请求拦截器

    // request拦截器
    service.interceptors.request.use(
      config => {
        if (store.getters.token) {
          config.headers['Authorization'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
        }
        return config
      },
      error => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
      }
    )
    

    3.2 使用 interceptors 配置响应拦截器

    // response 拦截器
    service.interceptors.response.use(
      response => {
        // code为非20000是抛错 可结合自己业务进行修改
        const res = response.data
        if (res.code !== 0 && res.statusCode !== '200') {
          Message({
            message: res.msg || res.message,
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject('error')
        } else {
          return response.data
        }
      },
      error => {
        console.log(error) // for debug
        if (error.response && error.response.status === 401) {
          MessageBox.confirm(
            '你已被登出,可以取消继续留在该页面,或者重新登录',
            '确定登出',
            {
              confirmButtonText: '重新登录',
              cancelButtonText: '取消',
              type: 'warning'
            }
          ).then(() => {
            store.dispatch('FedLogOut').then(() => {
              location.reload() // 为了重新实例化vue-router对象 避免bug
            })
          })
        } else {
          Message({
            message: error.message,
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject(error)
        }
      }
    )
    

    4 api 文件夹分模块封装请求方法

    4.1 页面中引入对应js文件

    4.2 页面中使用 -- 分模块封装的请求方法

    4.3 在 store 的模块中也可直接引入调用

  • 相关阅读:
    Chrome 无法登录 GitHub,响应时间过长,可行解决办法
    npm install报错 npm ERR! cb() never called! 检查镜像源!
    Win10 移动文件的时候“卡”在“正在暂停/取消”解决办法
    VS code 彻底关闭插件自动更新功能
    箭头函数 函数中的this指向
    ES6 ES6变量的声明
    范围内的拖拽事件
    div拖拽移动事件
    事件对象的属性 div点击移动事件
    tab切换之循环遍历
  • 原文地址:https://www.cnblogs.com/pleaseAnswer/p/14103627.html
Copyright © 2011-2022 走看看