繁体   English   中英

Vue.js 2 + Typescript - 全局变量在构建后变得未定义

[英]Vue.js 2 + Typescript - global variables becomes undefined after build

我有一个带有 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)

在我的localhost上工作时,它返回两倍相同的值,但是当我创建一个构建时它返回我:

Module {__esModule: true, Symbol(Symbol.toStringTag): "Module"}, undefined

类似的事情发生,当我添加console.log(urls, this.$urls) - 导入的模块被记录,而原型返回undefined

有什么想法吗? 将不胜感激任何帮助。

最后,我通过将原型部件从main.ts移动到App.ts文件来克服了这个问题。

我不能 100% 确定它是否是解决此问题的有效“Vue.js 方式”,因为我一直在main.js文件中声明这一点 - 但我当时使用的是 JavaScript 并且它按预期“正常工作”。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM