【问题标题】:Scope of Data in vue.js Modulevue.js 模块中的数据范围
【发布时间】: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


【解决方案1】:

this 现在属于传递给setInterval 的函数。

你有几个选择:

function onInterval () {
  if (this.userAccount) {
  //
  }
}

setInterval(onInterval.bind(this), 1000);

setInterval(() => {
  if (this.userAccount) {
    //
  }
}, 1000);

参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

在大多数情况下,this 的值取决于函数的调用方式(运行时绑定)。执行时不能通过赋值来设置,每次调用函数时可能都不一样。 ES5 引入了 bind() 方法来设置函数的 this 的值,而不管它是如何被调用的,ES2015 引入了不提供自己的 this 绑定的箭头函数(它保留了封闭词法上下文的 this 值)。

【讨论】:

  • 感谢您的回答和时间 Sturm。这行得通!
猜你喜欢
  • 2022-06-11
  • 1970-01-01
  • 2016-05-09
  • 2018-02-28
  • 2014-10-03
  • 2023-03-20
  • 2023-02-09
  • 2019-09-10
  • 2015-08-28
相关资源
最近更新 更多