Peterlits Zo
Peterlits Zo

Reputation: 536

Vue.js component do not change its HTML output by its data

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. ( •̀ ω •́ )✧

Upvotes: 0

Views: 65

Answers (1)

akuiper
akuiper

Reputation: 215117

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 
    })
}

Upvotes: 2

Related Questions