Vue equivalent of setTimeout?

前端 未结 13 2303
栀梦
栀梦 2021-01-30 08:20

I\'m making a shopping cart system with Laravel and Vue. When I add an item to the basket, I display a confirmation message by toggling a Vue variable being watched by a v-if:

13条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 08:45

    after encountering the same issue, I ended up on this thread. For future generation's sake: The current up-most voted answer, attempts to bind "this" to a variable in order to avoid changing the context when invoking the function which is defined in the setTimeout.

    An alternate and more recommended approach(using Vue.JS 2.2 & ES6) is to use an arrow function in order to bind the context to the parent (Basically "addToBasket"'s "this" and the "setTimeout"'s "this" would still refer to the same object):

    addToBasket: function(){
            item = this.photo;
            this.$http.post('/api/buy/addToBasket', item);
            this.basketAddSuccess = true;
            setTimeout(() => {
                this.basketAddSuccess = false;
            }, 2000);
        }
    

提交回复
热议问题