Answer the question
In order to leave comments, you need to log in
I have a variable in data g=1, I change its value, but the number g equal to 1 is still displayed, why?
beforeMount: function() {
let vm=this
firebase.auth().onAuthStateChanged(async function(user) {
if (user) {
let profileId=await user.uid
vm.profileId=profileId
this.g=5
}
})
},
Answer the question
In order to leave comments, you need to log in
this
internally function
depends on the context of the call to this function
.
When it fires onAuthStateChanged
, the handler function passed to it is called, which sets some this
(or not set, and then it is by default window
or, in strict mode, undefined
). And this one this
definitely has nothing to do with the current this
Vue, because it is not passed in any way when called, and, accordingly, onAuthStateChanged
knows nothing about it.
Use:
a) to hard-wire this function to .
b) , because thus the specific one is stored in a variable and does not change depending on the context of the call.
c) arrow function , its mechanics of work essentially implements an implicit(async function(user) { ... }).bind(this)
this
async (user) => { ... }
bind
.
d) handler function in Vue methods: Vue automatically makes bind
all methods to this:
onAuthStateChanged(this.onAuthStateChanged)
methods: {
onAuthStateChanged: async function (user) { ... }
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question