Vue 3 TS 全局配置最佳实践:使用 provide 和 inject
在 Vue 3 中,可以使用 'provide' 和 'inject' 来设置和获取全局配置。以下是示例代码:
import { provide, inject } from 'vue'
// 定义全局配置接口
interface GlobalConfig {
apiUrl: string
maxCount: number
}
// 在根组件中提供全局配置
const globalConfig: GlobalConfig = {
apiUrl: 'https://api.example.com',
maxCount: 10
}
provide('globalConfig', globalConfig)
// 在其他组件中获取全局配置
const config = inject<GlobalConfig>('globalConfig')
console.log(config.apiUrl) // 输出 https://api.example.com
使用 'provide' 提供全局配置后,可以通过 'inject' 在其他组件中获取该配置。在 'inject' 中需要传入一个泛型参数,指定需要获取的配置类型。以上示例中,泛型参数为 'GlobalConfig'。
原文地址: https://www.cveoy.top/t/topic/nQhe 著作权归作者所有。请勿转载和采集!