【发布时间】:2020-04-29 22:22:12
【问题描述】:
我的 vue.js 文件/模块中包含以下代码:
export default {
name: 'App',
data () {
return {
web3: null,
account: null,
contractInstance: null,
userAccount: null
}
},
mounted () {
web3Cont().then((res) => {
this.web3 = res
this.contractInstance = new this.web3.eth.Contract(contractAbi, contractAddress)
this.web3.eth.getAccounts().then((accounts) => {
[this.account] = accounts
console.log(accounts)
}).catch((err) => {
console.log(err, 'err!!')
})
})
setInterval(function () {
// Check if account has changed
if (this.userAccount !== this.account) {
this.account = this.userAccount
this.updateInterface()
}
}, 1000)
}
}
据我了解,在 data() 函数中导出的变量都应该在文件中具有“全局”范围。然而,虽然我在 web3Cont 函数中为“account”变量赋值,但在执行 setInterval 函数时,该值仍然未定义。
我错过了什么?
【问题讨论】:
-
您必须在设置的时间间隔内使用箭头函数才能访问此(或绑定到此)。所以: setInterval(() => { this is defined}) 此外,你应该在销毁时清除你的间隔
标签: javascript node.js vue.js ethereum metamask