VUE2.0项目实现打包后接口地址可配置

VUE2.0项目实现打包后接口地址可配置

  • 1.编写配置文件
  • 2.读取配置文件

1.编写配置文件

配置文件推荐使用JSON格式,可读性更好。文件路径例如:public/config/config.json。

{
  "serverUrl": "/prod-api",
  "baidu":"https://www.baidu.com"
}

2.读取配置文件

在public/index.html增加读取配置文件的代码。根据业务要求,存入sessionStorage或者localStorage,在其他需要的地方进行使用。

   //获取配置文件信息
        if(!sessionStorage.getItem("serverUrl")){
            let xhr=new XMLHttpRequest();
            xhr.open("GET","/config/config.json");
            xhr.send(null)
            xhr.onreadystatechange=()=>{
                if(xhr.status===200&&xhr.readyState===4){
                    let config=JSON.parse(xhr.responseText);
                    Object.keys(config).forEach(key=>sessionStorage.setItem(key,config[key]));
                }
            }
        }

你可能感兴趣的:(vueJs,json,java,javascript)