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>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
2019-07-24 C#子线程执行完后,调用主线程的方法
2015-07-24 javascript 中 split 函数分割字符串成数组
2015-07-24 javascript中 try catch finally 的使用
2015-07-24 JavaScript中的枚举
2012-07-24 MySQL字符串中数字排序的问题