0

Firstly, I have a sub-component like this:

Vue.component("banana", {
    props: {bid: Number} // bid: means Banana's id
    data () {
        return {
            OK: true
        }
    },
    mounted () {
        this.do_a_sync_thing() // do a sync function when it is mounted
    },
    methods: {
        do_a_sync_thing () {
            setTimeout(function() {
                this.OK = true // [ERROR]: WHY the output do not change to {{ pid }} 
                               //          but still is "NO OK, Loading..."
            })
        }
    },
    template: `
        <div>
            <template v-if="OK">
                {{ bid }}
            </template>
            <template v-else>
                NO OK, Loading...
            </template>
        </div>`
})

Then I text this in HTML file:

<banana id="app" :bid="8"></banana>

And this in JS file:

var app = new Vue({
    el: "#app",
    data: {}
})

So the question is: why the template output do not change after I change its data?

Thank you. ( •̀ ω •́ )✧

2
  • 1
    Function has its own this context, bind context, or arrow Commented Aug 8, 2020 at 6:46
  • Thanks you @Estradiaz ~ I think I get it~ Commented Aug 8, 2020 at 6:55

1 Answer 1

2

In setTimeout, the anonymous function override this, so this in the function doesn't point to the Vue component anymore. You can use an arrow function to avoid the override:

do_a_sync_thing () {
    setTimeout(() => {
        this.OK = true 
    })
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.