I am declaring a “userid” variable in the data() section of my component. Within a mounted() method, I am initiating a listener for MetaMask. Upon changing account in MetaMask this listener is triggered. However, the “userid” (declared in data()) within the listener is undefined.
JavaScript
x
15
15
1
export default {
2
name: 'App',
3
data () {
4
return {
5
userid: null
6
}
7
},
8
mounted () {
9
10
// MetaMask Listener
11
window.ethereum.on('accountsChanged', function (accounts) {
12
this.userid = accounts
13
})
14
}
15
How can I solve this problem?
Advertisement
Answer
Vue runs in strict
mode. That means that this
is binded to regular function itself.
You have 3 ways to solve this problem:
Use arrow function:
JavaScript
1
4
1
window.ethereum.on('accountsChanged', accounts => {
2
this.userid = accounts
3
})
4
Use .bind()
JavaScript
1
4
1
window.ethereum.on('accountsChanged', function (accounts) {
2
this.userid = accounts
3
}.bind(this))
4
Declare a variable outside and assign this
to it:
JavaScript
1
5
1
var self = this;
2
window.ethereum.on('accountsChanged', function (accounts) {
3
self.userid = accounts
4
})
5