Vue equivalent of setTimeout?

前端 未结 13 2315
栀梦
栀梦 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

    Arrow Function

    The best and simplest way to solve this problem is by using an arrow function () => {}:

        addToBasket() {
            var item = this.photo;
            this.$http.post('/api/buy/addToBasket', item);
            this.basketAddSuccess = true;
            // now 'this' is referencing the Vue object and not the 'setTimeout' scope
            setTimeout(() => this.basketAddSuccess = false, 2000);
        }
    

    This works because the this of arrow functions is bound to the this of its enclosing scope- in Vue, that's the parent/ enclosing component. Inside a traditional function called by setTimeout, however, this refers to the window object (which is why you ran into errors when you tried to access this.basketAddSuccess in that context).

    Argument Passing

    Another way of doing this would be passing this as an arg to your function through setTimeout's prototype using its setTimeout(callback, delay, arg1, arg2, ...) form:

        addToBasket() {
            item = this.photo;
            this.$http.post('/api/buy/addToBasket', item);
            this.basketAddSuccess = true;
            //Add scope argument to func, pass this after delay in setTimeout
            setTimeout(function(scope) {
                 scope.basketAddSuccess = false;
            }, 2000, this);
        }
    

    (It's worth noting that the arg passing syntax is incompatible with IE 9 and below, however.)

提交回复
热议问题