Files
zyt/TUICallKit-Vue3/utils/global.js
T
2026-03-11 14:33:49 +08:00

111 lines
2.4 KiB
JavaScript

/**
* 全局属性工具函数
* 用于在任何地方访问 main.js 中定义的全局属性
*/
import { getCurrentInstance } from 'vue'
/**
* 获取全局属性对象
* @returns {Object} 全局属性对象
*/
export const getGlobalProperties = () => {
try {
const instance = getCurrentInstance()
if (instance) {
return instance.appContext.config.globalProperties
}
} catch (e) {
console.warn('无法获取 getCurrentInstance:', e)
}
return {}
}
/**
* 获取 API 基础 URL
* @returns {string} API 基础 URL
*/
export const getBaseUrl = () => {
const globalProps = getGlobalProperties()
return globalProps.$url || 'http://api.zzzhengyangtang.cn'
}
/**
* 获取 apiUrl 方法
* @returns {Function} apiUrl 方法
*/
export const getApiUrl = () => {
const globalProps = getGlobalProperties()
return globalProps.apiUrl
}
/**
* 使用全局属性的 Composition API Hook
* @returns {Object} 包含全局属性的对象
*/
export const useGlobal = () => {
const globalProps = getGlobalProperties()
return {
// API 相关
baseUrl: globalProps.$url || 'http://api.zzzhengyangtang.cn',
apiUrl: globalProps.apiUrl,
// 应用相关(可选)
appName: globalProps.$appName,
version: globalProps.$version,
// 其他全局属性
...globalProps
}
}
/**
* 获取完整的 API URL
* @param {string} path - API 路径
* @returns {string} 完整的 API URL
*/
export const getFullUrl = (path) => {
const baseUrl = getBaseUrl()
return `${baseUrl}${path}`
}
/**
* 设置全局属性(谨慎使用)
* @param {string} key - 属性名
* @param {any} value - 属性值
*/
export const setGlobalProperty = (key, value) => {
try {
const instance = getCurrentInstance()
if (instance) {
instance.appContext.config.globalProperties[key] = value
return true
}
} catch (e) {
console.error('无法设置全局属性:', e)
}
return false
}
/**
* 获取特定的全局属性
* @param {string} key - 属性名
* @param {any} defaultValue - 默认值
* @returns {any} 属性值
*/
export const getGlobalProperty = (key, defaultValue = null) => {
const globalProps = getGlobalProperties()
return globalProps[key] !== undefined ? globalProps[key] : defaultValue
}
export default {
getGlobalProperties,
getBaseUrl,
getApiUrl,
useGlobal,
getFullUrl,
setGlobalProperty,
getGlobalProperty
}