Vue2 打包部署后通过修改配置文件修改全局变量——实时生效

1、需求说明

在生产实践中,经常会遇到需要对系统的功能或表现样式做一些更改,网上有些例子:

1)比如使用copy组件拷贝到public,生产验证失败。

2)将配置放在public下的js中,按需应用,生产验证失败。

我这里提供一种简单的实现方法:

在main.js中通过axios获取json数据后挂载到app中,这样在组件中可以通过 this 来方便的访问。

2、实现方法

1)新建json配置文件

在yudao-ui-admin-vue2\public\下新建setting.json,内容只要是json格式就行,例如:

java 复制代码
{
  "drawerWidthEnabled": true,
  "reportServer": "http://192.168.1.222:3000/big"
}

2)修改 vue 实例化过程

在src\main.js的末尾处将 app的初始化过程修改为:

java 复制代码
//要引入axios才能用
//注意获取config.json的地址
import axios from 'axios'
axios.get(process.env.VUE_APP_PUBLISH_PATH + "uhr_setting.json").then((resp)=>{
  var conf = resp.data;
  Vue.prototype.setting = conf
  app = new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
  })
}).catch((error)=>{console.log(error)});

process.env.VUE_APP_PUBLISH_PATH来自于 .env.xxx配置文件 ,表示应用发布路径,经常是二级发布目录,如数据大屏: /big/,这样要注意一下最后有个反斜杠 /

3)在组件中使用

组件中直接通过this.setting来访问配置属性,非常方便。

java 复制代码
<template>
  <div class="">
    <doc-alert v-if="0" title="大屏设计器" url="https://doc.iocoder.cn/report/screen/" />
    <i-frame v-if="url" :src="url" />
  </div>
</template>
<script>
import iFrame from "@/components/iFrame/index";
import { setTenantId, getTenantId} from "@/utils/auth";
export default {
  name: "BigScreen",
  components: { iFrame },
  props: {
    /* 数据大屏的id */
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      url: undefined,
    };
  },
  mounted(){
    var reportId = this.$route.params.id || this.$route.query.id || this.value
    if(reportId){
      this.url =  this.setting.reportServer + "/chart/preview/"+reportId+"?sso=true"
    } else {
      this.url = this.setting.reportServer + "/?sso=true";
    }
  }
};
</script>
相关推荐
VT.馒头1 小时前
【力扣】2637. 有时间限制的 Promise 对象
前端·javascript·leetcode·typescript
灵犀坠1 小时前
Vue3 实现音乐播放器歌词功能:解析、匹配、滚动一站式教程
开发语言·前端·javascript·vue.js
north_eagle1 小时前
ReAct 框架详解
前端·react.js·前端框架
OEC小胖胖1 小时前
13|React Server Components(RSC)在仓库中的落点与边界
前端·react.js·前端框架·react·开源库
OEC小胖胖1 小时前
14|Hook 的实现视角:从 API 到 Fiber Update Queue 的连接点
前端·react.js·前端框架·react·开源库
军军君012 小时前
Three.js基础功能学习十:渲染器与辅助对象
开发语言·前端·javascript·学习·3d·前端框架·ecmascript
Marshmallowc2 小时前
React useState 数组 push/splice 后页面不刷新?深度解析状态被『蹭』出来的影子更新陷阱
前端·react.js·前端框架
GIS之路2 小时前
ArcGIS Pro 添加底图的方式
前端·数据库·python·arcgis·信息可视化
Mo_jon2 小时前
vite + vue 快速构建 html 页面 (舒适编写html文件)
前端·vue.js·html