vue.js 模块中的数据范围
Scope of Data in vue.js Module
我的 vue.js file/module 中包含以下代码:
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 函数时该值仍然未定义。
我错过了什么?
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。
In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).
我的 vue.js file/module 中包含以下代码:
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 函数时该值仍然未定义。
我错过了什么?
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。
In most cases, the value of this is determined by how a function is called (runtime binding). It can't be set by assignment during execution, and it may be different each time the function is called. ES5 introduced the bind() method to set the value of a function's this regardless of how it's called, and ES2015 introduced arrow functions which don't provide their own this binding (it retains the this value of the enclosing lexical context).