Dynamic checkbox does not work (Vuejs)

Asked

Viewed 251 times

0

I am developing a Feature that lists products and their status (enabled, disabled). To choose the state of the product, I am using a checkbox in toggle-switch format.

<div class="col-md-6 col-xl-10" v-for="product in products" :key="product.id">
.
.
.

<i class="custom-control custom-switch">
  <input type="checkbox" class="custom-control-input" :id="product.id" v-model="product.status">
  <label class="custom-control-label" for="customSwitches"> {{ product.status }} </label>
</i>

To make this checkbox dynamic, I tried to use the checkbox with the id referencing the product :id="product.id".

The problem that when I used this way, the checkbox stops working, is always false and by clicking it does not change the state (nor graphically).

1 answer

1


You did not create an event to change the status. You can do this using the v-on:click or shortened @click directive as in the example below:

<i class="custom-control custom-switch" @click="product.status = !product.status">
...
</i>

new Vue({
  el: "#app",
  data() {
    return {
      products: [
        {
          id: 1,
          status: true
        },
        {
          id: 2,
          status: false
        }
      ]
    };
  }
});
@import url('https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.4.1/css/bootstrap.min.css')
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  
  <div class="col-md-6 col-xl-10" v-for="product in products" :key="product.id">

<i class="custom-control custom-switch" @click="product.status = !product.status">
  <input type="checkbox" class="custom-control-input" v-model="product.status" >
  <label class="custom-control-label" for="customSwitches"> {{ product.status }} </label>
</i>
  
</div>

  • Thank you very much! Solved here!

  • You can use the @change directive in this input?

  • 1

    @Matheuscosta No. But you can hear a change event in the input or else extract the inline assignment for a method and create the rule you want

Browser other questions tagged

You are not signed in. Login or sign up in order to post.