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>
相关推荐
狂师7 小时前
太强了!GitHub上开源了一款AI自动化测试框架,0代码搞定前后端测试!
前端·后端·测试
只睡四小时7 小时前
Local-First 数据契约:一张表装下 4 类数据
前端·javascript·架构设计·local-first·数据契约
迅猛龙办公室7 小时前
Python函数实现反转一个只有3位数的整数
开发语言·前端·python
我星期八休息7 小时前
Redis 的原理和使用(2)
前端·数据库·redis·python·mysql·缓存·bootstrap
Java后端的Ai之路7 小时前
19-ReactJS最佳实践
前端·react.js·前端框架
溪语流沙7 小时前
【Web全栈进阶】文件上传与图片展示:早报站的第一张图片
前端·vue.js·python·fastapi
alwaysrun7 小时前
Web之wasm-bindgen详解
前端·wasm·bindgen
鬼手点金7 小时前
如何选择模型
java·前端·人工智能·git·深度学习
恋猫de小郭7 小时前
Dart 3.15 新特性:this 终于支持类型提升了
android·前端·flutter
IT_陈寒8 小时前
Vue开发实战:从入门到精通
前端·人工智能·后端