在vue工程里使用env环境配置文件设置的全局变量,一般都是通过process.env.变量名获取,这里结合使用TypeScript的装饰器实现了一种更优(zhuang)雅(bi)的写法
.env文件
NODE_ENV = development
VUE_APP_ServerHost = http://localhost:8080/geoserver/
VUE_APP_ServerName = basic-platform
装饰器定义
import Vue from 'vue';
/**
* 获取全局变量
* @param name env文件里去掉VUE_APP_前缀的变量key,未指定就使用变量名
* @returns 变量值
*/
export function GlobeConfig(name?: string) {
return function (_target: any, _attr: string) {
const info = process.env[`VUE_APP_${name || _attr}`];
if (!info) {
throw `环境变量 VUE_APP_${name || _attr} 不存在`;
}
if (_target instanceof Vue) {
_target.$set(_target, _attr, info);
} else {
_target[_attr] = info;
}
};
}
在vue组件内的使用
import { GlobeConfig } from '@/extension/decorators';
@Component
export default class OLMap extends Vue {
@GlobeConfig()
private ServerHost!: string; // 输出http://localhost:8080/geoserver/
@GlobeConfig('ServerName')
private serverNameSpace!: string; // 输出basic-platform
}
其他装饰器的使用示例见TypeScript装饰器示例