Vue 开发样板中的随机错误"ethereum is not defined"



我正试图使用使用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启动环境时,当我更改组件中的一些代码时,我在测试窗口和终端中都会出现以下错误:

编译失败。

/src/App.vue模块错误(来自./node_modules/eslin-loader/index.js(:

/home/arnad/Code/_BLOCKCHAIN/crypto-app/src/app.vue 16:30错误"以太坊"未定义无未定义

1个问题(1个错误,0个警告(

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

首先安装元任务扩展,然后检查类似的以太坊实例

const {ethereum} =window;

这是一个esint错误,因为您试图在未在中声明的作用域中使用ethereum变量。如果ethereum已在全局作用域中声明。您可以禁用该行的esint。

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。

相关内容

最新更新