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>
相关推荐
Alice-YUE5 小时前
【js高频八股】防抖与节流
开发语言·前端·javascript·笔记·学习·ecmascript
是上好佳佳佳呀6 小时前
【前端(十一)】JavaScript 语法基础笔记(多语言对比)
前端·javascript·笔记
CDN3606 小时前
排查实录:网站偶发502/504错误?360CDN回源超时配置与日志分析技巧
前端·数据库
之歆7 小时前
Day07_CSS盒子模型 · 样式继承 · 用户代理样式
前端·css
DanCheOo7 小时前
AI 应用的安全架构:Prompt 注入、数据泄露、权限边界
前端·人工智能·prompt·安全架构
We་ct8 小时前
深度剖析浏览器跨域问题
开发语言·前端·浏览器·跨域·cors·同源·浏览器跨域
weixin_427771618 小时前
前端调试隐藏元素
前端
爱上好庆祝9 小时前
学习js的第五天
前端·css·学习·html·css3·js
C澒10 小时前
IntelliPro 产研协作平台:基于 AI Agent 的低代码智能化配置方案设计与实现
前端·低代码·ai编程
一袋米扛几楼9810 小时前
【Git】规范化协作:详解 GitHub 工作流中的 Issue、Branch 与 Pull Request 最佳实践
前端·git·github·issue