vue3.0 外部配置文件一 (导入json文件方式)
vue3.0 外部配置文件,重点是打包后也可以 修改配置参数
注:js文件中必须是标准的 json 格式
一、在public中创建static文件夹,在static文件夹中创建 config.json 文件

config.json (必须是标准的 json 格式)
{ "webSocketUrl": "ws://192.168.1.120:5011/chat/", "userTel": "1001" }
二、在 man.js 中读取 并赋给全局变量
采用 导入 json 文件的方式
import { createApp } from 'vue'
import { reactive } from 'vue'
import App from './App.vue'
import {webSocketUrl} from '/public/static/config.json'
import {userTel} from '/public/static/config.json'
const app = createApp(App);
//全局对象
const globalData=reactive({
missedCallData:"",
currentUserTel:"",
})
app.provide('globalData', globalData);
//读配置文件
app.config.globalProperties.$webSocketUrl=webSocketUrl;
console.log('读配置文件====',app.config.globalProperties.$webSocketUrl);
globalData.currentUserTel= userTel;
console.log('读配置文件====',globalData.currentUserTel);
其中用到了两种不同的全局变量方式
全局变量 app.config.globalProperties 方式
在main.js 文件中的用法
console.log('读配置文件====',app.config.globalProperties.$webSocketUrl);
在 子组件中的用法
console.log("全局变量 "+ this.$webSocketUrl);
响应式全局对象方式
在main.js 文件中的用法
console.log('读配置文件====',globalData.currentUserTel);
在 子组件中的用法 响应式
<template>
<div class="IndConF flexC">
<div>分机号:{{this.globalData.currentUserTel}} </div>
<a href="javascript:;" class="IndConFa flexC fl-cen" v-on:click="Hangup_onClick()"><i class="IndConFI IndConFI2"></i><p>挂断</p></a>
</div>
</template>
<script>
// 在子组件中注入全局对象
import { inject, watch } from 'vue'
export default {
// 组件名称
name: 'FootComponent',
setup() {
// 注入全局对象
const globalData = inject('globalData');
watch(() => globalData.currentUserTel, (newValue) => {
// 更新
globalData.currentUserTel=newValue;
//console.log("SoftPhoneComponent watch "+newValue);
})
return {
globalData
};
},
methods: {
Hangup_onClick(){
var exttel=this.globalData.currentUserTel;
console.log("响应式全局对象 "+ this.globalData.currentUserTel);
},
}
}
</script>

浙公网安备 33010602011771号