Vue3 运行可以,build 打包发布报错,app.config.globalProperties 用法坑
app.config.globalProperties 用法坑Vue,
多环境配置 https://www.cnblogs.com/vipsoft/p/16696640.html
main.js
import config from '@/utils/config'
//这是对 Vue 2 中 Vue.prototype 使用方式的一种替代,此写法在 Vue 3 已经不存在了。与任何全局的东西一样,应该谨慎使用。
app.config.globalProperties.$config = config
错误原因
config.js
const config = {
title: '管理系统(开发)', //开发、测试
apiUrl: 'http://www.vipsoft.com.cn',
version: 'v1.0.1'
}
export default config
vue
login\index.vue
<h3 class="title">{{this.$config.title}}</h3>
报错
main.js:32 TypeError: Cannot read properties of undefined (reading '$config')
at chunk-f033586a.20f75701.js:1:1719
at r (runtime-core.esm-bundler.js:827:13)
at Er (runtime-core.esm-bundler.js:2973:53)
at Proxy.ih (index.js:217:5)
at Jt (runtime-core.esm-bundler.js:887:16)
at d.i [as fn] (runtime-core.esm-bundler.js:6020:46)
at d.run (reactivity.esm-bundler.js:177:19)
at L.e.update (runtime-core.esm-bundler.js:6151:16)
at L (runtime-core.esm-bundler.js:6161:5)
at A (runtime-core.esm-bundler.js:5929:7)
解决方案
login\index.vue
<h3 class="title">{{config.title}}</h3>
<script>
import { ref,getCurrentInstance} from 'vue'
export default {
setup(){
const instance = getCurrentInstance()
const config = instance?.appContext.config.globalProperties.$config;
return {
config
}
}
}
</script>
简化写法
<script setup>
import { ref,getCurrentInstance} from 'vue'
const instance = getCurrentInstance()
const config = instance?.appContext.config.globalProperties.$config;
</script>
https://cn.vuejs.org/api/sfc-script-setup.html
<script setup>
是在单文件组件 (SFC) 中使用组合式 API 的编译时语法糖。当同时使用 SFC 与组合式 API 时该语法是默认推荐。相比于普通的
本文来自博客园,作者:VipSoft 转载请注明原文链接:https://www.cnblogs.com/vipsoft/p/18241862
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 清华大学推出第四讲使用 DeepSeek + DeepResearch 让科研像聊天一样简单!
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
2021-06-11 Nacos 服务状态监听四种写发
2012-06-11 UML中的五种关系