How to execute function when input loses focus in vue

Viewed 433

I have an input field and there, the amount can be entered. So my target is to when the user clicks outside of the input field, update the cart.

<div v-for="item in cart.attributes.items" :key="item.id">
                <div class="row">
                    <div class="col-lg-10 col-md-10 col-sm-10 col-xs-10 cart-items">
                        <strong>{{ item.product_name }}</strong>
                        <br/>
                        <div class="number-of-tickets">
                            <input id="cart_amount" type="number" min="1" class="col-1 form-control cart-input" v-model="item.amount">
                            <div> x € {{ item.price_excl_vat }}</div>
                        </div>
                    </div>
                    <div class="col-lg-2 col-md-2 col-sm-2 col-xs-2">
                        <a class="remove" @click.prevent="removeProductFromCart(item.id)"><i class="far fa-trash-alt"></i></a>
                    </div>
                </div>
            </div>

So as you see here, there is an input field with the v-model "item-amount". Also this is my function to fetch data:

updateCart(id, amount) {
            cartHelper.updateCart(id, amount, (response) => {
                this.$store.dispatch('updateProductsInCart', {
                    cart: response.data,
                })
            });
        }

So whenever when I click the outside of the input field, I want to render updateCart function with the amount of input field.

1 Answers

What you want is to update the cart amount as soon as you leave the field.

You have the html event blur made just for this:

<input 
  id="cart_amount"
  @blur="updateCart(/* right params */)"
  ...>

The event triggers as soon as the input loses focus.

Related