javascript - Vue.js 2 + Typescript - 全局变量在构建后变得未定义
问题描述
我有一个带有 Typescript 的 Vue.js 2 项目。在main.ts
文件中,我声明了 2 个变量,我想在我的项目中全局访问它们:
// ...
Vue.prototype.$http = http; // this is the library imported from another file, contains various methods such as `get`, `post` etc.
Vue.prototype.$urls = urls; // this is JSON object, also imported from another file
new Vue({
store,
render: (h) => h(App),
}).$mount('#app');
在我的一个组件中,我们称它为User
我有以下mounted
代码块:
mounted(): void {
this.$http.get(`${this.$urls.getUser}/${this.userId}`);
}
当我运行本地服务器(通过npm run serve
命令)时一切正常,但是当我创建应用程序构建(通过npm run build
命令)并在服务器上输入应用程序(或index.html
我的硬盘上的文件)时,我收到以下错误:
TypeError: Cannot read property 'get' of undefined
at VueComponent.value (user.ts:62) // <-- this line is the one with $http.get from `mounted` hook
我不确定如何进行此操作,我盲目地尝试将这些全局值添加到各个位置,例如在http.d.ts
文件中我有以下内容:
import { KeyableInterface } from '@/interfaces/HelperInterfaces';
import Vue from 'vue';
declare module 'vue/types/vue' {
interface VueConstructor {
$http: KeyableInterface;
}
}
declare module 'vue/types/vue' {
interface Vue {
$http: KeyableInterface;
}
}
declare module 'vue/types/options' {
interface ComponentOptions<V extends Vue> {
http?: KeyableInterface
}
}
(我也urls.d.ts
用类似的代码创建过)
更新#1:
我也尝试过以下方法 - 在我的main.ts
文件中:
const helperModules = {
/* eslint-disable-next-line @typescript-eslint/no-explicit-any */
install: (vueInstance: any) => {
vueInstance.prototype.$http = http;
vueInstance.prototype.$urls = urls;
},
};
Vue.use(helperModules);
但它仍然不起作用(同样的错误)。
更新#2:
我还将http
实用程序导入到我的user
组件中,并console.log
在现有mounted
回调中添加了以下内容:
console.log(http, this.$http)
在处理 mylocalhost
时,它会返回两倍相同的值,但是当我创建构建时,它会返回:
Module {__esModule: true, Symbol(Symbol.toStringTag): "Module"}, undefined
类似的事情发生了,当我添加console.log(urls, this.$urls)
- 导入的模块被记录,而原型返回时undefined
。
有什么想法吗?将不胜感激任何帮助。
解决方案
最后,我通过将原型部件从文件移动main.ts
到App.ts
文件来克服了这个问题。
我不能 100% 确定它是否是解决这个问题的有效“Vue.js 方式”,因为我一直在main.js
文件中声明 - 但我当时使用的是 JavaScript,它按预期“正常工作”。
推荐阅读
- android - 没有java的android NDK adb可执行文件
- mysql - 类别、子类别和服务的数据库结构
- javascript - 嵌套函数和未定义值中的“this”问题
- ios - Ionic iOS - 复制一些 HTML 视频后变黑
- django - Django Table - 加载数据表,访问值
- android - 关键帧需要 webrtc android 应用程序中的第一个错误。如何降低传入视频的帧率?
- typescript - 将图像上传到 Firestore 存储时出现问题
- arrays - 合并 Yaml 数组嵌套
- python-3.x - 训练损失和准确率不会改变——停留在一个值附近——Tensorflow
- python - 如何在python中找到掷骰子程序的最小值和最大值