Vue实战中遇到的常见的问题总结(一)

415 阅读2分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第1天,点击查看活动详情

交代开发背景

目前项目基于vue2.0,使用vue-cli4以及element UI进行的搭建。
在工作开发过程中,经常会遇到一些比较常见问题,或一些比较麻烦的操作导致开发难度增大,经摸索踩坑,做了一些封装和记录并总结如下。

axios封装和api接口统一

关于axios的封装,分为两个方面
一个是对请求(request)的拦截:利用request拦截器可以统一校验是否携带token等操作,如下:

axios.interceptors.request.use(
   (config) => {
     // 验证token
     if(localStorage.getItem("token")==null){
       config.headers.Authorization =''
     }
     else{
       config.headers.Authorization =localStorage.getItem("token");
     }
     return config
   },
   (err) => {
      return Promise.reject(err)
   },
)

一个是对响应(response)的拦截:利用response拦截器可以根据状态码来进行错误的统一处理等等,如下:

axios.interceptors.response.use(
 (response) => {
     return response
  },
  (error) => {
    //需根据实际返回格式
       if (error.response.data.status_code) {
       switch (error.response.status) {
           case 404:
               /**错误处理
                vueObj.$message({
                 message: error.response.data.message,
                 type: 'warning'
               });
               */
               break;
           case 401:
              /**错误处理
               localStorage.removeItem("token");
               router.replace('/');
               */
               break; 
       }
     }
    return Promise.reject(error)
  },
)

关于api接口的统一管理,本人对常用的是get和post方法进行封装,是为了方便接口管理,简化代码,更好的编写业务,更有利于维护。如下:

import qs from "qs";
import axios from "axios"
export function get(url, param,successFunction,errorFunction) {
    /*根据项目中是否有该需要---将提交参数为空时删掉该字段
    Object.keys(param).forEach(function(key){
      if(param[key] === "" || param[key] == null ||param[key] == undefined) {
        delete param[key];
      }
    });*/
  const Host = xxx;
  axios.get(Host+url,{params:param},successFunction)
    .then((response)=> { 
      successFunction(response);
    })
    .catch((res)=>{
      if(typeof(errorFunction) == 'function'){
        errorFunction(res);
      }
    })
}

export function post(url,param,successFunction,type,config,errorFunction) {
   /*根据项目中是否有该需要---将提交参数为空时删掉该字段
  Object.keys(param).forEach(function(key){
    if(param[key] === "" || param[key] == null ||param[key] == undefined) {
        delete param[key];
    }
    });
    */
    if(type=="formData"){
       var config = {
       headers: {'Content-Type': 'multipart/form-data'}
       }
    }else{
      param = qs.stringify(param ? param : {})
    }
    /** 根据项目需要是否需要在提交post请求时弹出加载框
    const loading = vueObj.$loading({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0)'
    });
*/  
    const Host = xxx;
    axios.post(Host+url,param,config)
    .then((response)=> {
      successFunction(response);
      //loading.close();
    }).catch((res)=>{
      //loading.close();
      if(typeof(errorFunction) == 'function'){
        errorFunction(res);
      }
    })
}

本地开发环境出现跨域问题

在本地开发环境中,经常会遇到跨域的问题。这是因为本地开发环境下,去请求服务器接口的时候,由于客户端的同源策略,从而引起了跨域。那么我们可以通过跨域代理来解决这个问题。 解决方案如下:
首先在vue.config.js中增加以下代码:

devServer: {
        compress: true,
        disableHostCheck: true, //webpack4.0 开启热更新
        host: "0.0.0.0",
        port: 8080,
        // https: true,
        //open: true,
        hot: true,
        overlay: {
          warnings: true,
          errors: true
        },
        proxy: {
            "/api": {
                target: "http://120.xx.xx.xx:xxxx", //填写你调用的接口ip/域名及端口号
                 ws: true,
                changeOrigin: true,
                pathRewrite: {
                    "^/api": ""
               }
            }
        }
      }

在发起请求时,地址需要改写如下:

 const debug = process.env.NODE_ENV !== 'production'//首先判断是否为生产环境
 const Host = debug ? 'api' :process.env.VUE_APP_URL
    axios.post(Host+url,param,config)
    .then((response)=> {
      }).catch((res)=>{ 
      }
})

然后重新run一下项目。
则发起请求时会变成如下情况:返回200即为成功

image.png

打包后生成大量带.map文件

在vue.config.js配置 productionSourceMap为false即可
productionSourceMap选项是否在构建生产包时生成 sourceMap 文件,所以将其置为false,将会提高构建速度。

image.png