【问题标题】:Vue.js 2 + Typescript - global variables becomes undefined after buildVue.js 2 + Typescript - 全局变量在构建后变得未定义
【发布时间】:2021-04-01 15:49:03
【问题描述】:

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

有什么想法吗?将不胜感激。

【问题讨论】:

  • 您是否使用Vue.extend 创建组件?
  • @BoussadjraBrahim 你到底是什么意思? (我不是 100% 确定,但我假设我不在那里使用 Vue.extend)。我正在创建一个 Vue.js SPA,我想在其中的所有组件中使用全局变量。我过去做过,但这是我的第一个 TypeScript 项目,我看到文档中的指南在构建后在这种情况下不起作用。
  • Vue.extend 是在使用 TS 时需要得到推断的类型,但我建议尝试使用对 TS 支持非常好的 vue 3

标签: javascript typescript vue.js vuejs2


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-01
    • 2019-04-08
    • 2018-09-17
    • 1970-01-01
    相关资源
    最近更新 更多