F
F
Farkl2022-01-29 12:43:39
JavaScript
Farkl, 2022-01-29 12:43:39

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

1 answer(s)
A
Aetae, 2022-01-29
@Farkl

thisinternally functiondepends 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 windowor, in strict mode, undefined). And this one thisdefinitely has nothing to do with the current thisVue, because it is not passed in any way when called, and, accordingly, onAuthStateChangedknows 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 bindall methods to this:

onAuthStateChanged(this.onAuthStateChanged)
methods: {
  onAuthStateChanged: async function (user) { ... }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question