【问题标题】:Vue 开发样板中的随机错误“未定义以太坊”
【发布时间】:2022-01-19 02:53:32
【问题描述】:

如果这是一个愚蠢的问题,我深表歉意,但我才刚刚开始修补 Vue 和 web3!

我正在尝试使用用 vue-cli 创建的 Vue 基本样板在一个非常基本的 Vue3 组件中实现 web3,但我遇到了一些奇怪的错误。

首先,这是我的组件的代码:

<template>
  <img alt="Vue logo" src="./assets/images/logo.png">
  <pre v-if="account">{{ account }}</pre>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      account: undefined
    }
  },
  async mounted() {
    if (typeof ethereum !== 'undefined') {
      const accounts = await ethereum.request({ method: 'eth_requestAccounts' })
      this.account = accounts[0]
    }
  }
}
</script>

我遇到的第一个问题是,当我使用 npm run serve 启动环境并更改组件中的某些代码时,我的测试窗口和终端中出现以下错误:

Failed to compile.

./src/App.vue
Module Error (from ./node_modules/eslint-loader/index.js):

/home/arnaud/Code/_BLOCKCHAIN/crypto-app/src/App.vue
  16:30  error  'ethereum' is not defined  no-undef

✖ 1 problem (1 error, 0 warnings)

第二个奇怪的行为是,在启动环境时,有时我的终端中也会出现此错误,但有时不会。当我在启动时没有错误时,并且如果我不更改代码中的任何内容,我的应用程序似乎可以正常运行。

我已经进行了一些研究,但目前我没有找到任何对我有帮助的东西:/

【问题讨论】:

  • const { 以太坊 } = 窗口;加上元掩码

标签: vue.js web3 metamask


【解决方案1】:

先安装元掩码扩展,然后检查以太坊实例

const {ethereum} =window;

【讨论】:

  • 这解决了我的问题 :) 谢谢!
【解决方案2】:

这是一个 eslint 错误,因为您试图在未声明的范围内使用以太坊变量。如果以太坊已在全局范围内声明。您可以禁用此行的 eslint。

async mounted() {
      // eslint-disable-next-line no-undef
    if (typeof ethereum !== 'undefined') {
      // eslint-disable-next-line no-undef
      const accounts = await ethereum.request({ method: 'eth_requestAccounts' })
      this.account = accounts[0]
    }

否则你将不得不在组件中定义/导入以太坊。

【讨论】:

  • 感谢您的回答!实际上ethereum 是一个通过 Metamask 浏览器扩展注入到网页中的对象。我认为它一定会因为某种原因与 eslint 混淆:/
  • 确实,编辑了我的答案,现在应该可以了。只需添加 // eslint-disable-next-line no-undef
猜你喜欢
  • 2019-10-22
  • 2021-07-17
  • 2020-11-13
  • 2019-12-03
  • 2022-10-20
  • 2021-12-16
  • 2019-02-27
  • 2016-02-28
  • 1970-01-01
相关资源
最近更新 更多