El_Matella
3 years ago
294
7
Vue

Checkboxes and v-model

Posted 3 years ago by El_Matella

Hi, I am trying to make a small script using Vue, but I am having some problems.

First, here is a jsFiddle that shows my problem: https://jsfiddle.net/El_Matella/s2u8syb3/

Now, basically, I want to use a computed property on a checkbox. So for the moment I have:

<input v-model="isSelected(product)" v-on:click="toggleProduct(product)" type="checkbox">

Here is my computed isSelected function:

compute: {
    isSelected: function(product){
        for(var i = 0; i < this.selectedProducts.length; i++){
        if(this.selectedProducts[i].id == product.id) {
          return true;
        }
      }
      return false;
    }
  }

Here is my toggleProduct function:

methods: {
    toggleProduct: function(product){
        for(var i = 0; i < this.selectedProducts.length; i++){
        if(this.selectedProducts[i].id == product.id) {
          this.selectedProducts.splice(i,1);
          return true;
        }
      }
      this.selectedProducts.push(product);
    }
  },

And here is my example data:

data: {
    products:[{id:1},{id:2}],
    selectedProducts:[]
  },

The goal is to make a selection module, and selectedProducts should contain the products that have been selected. But the checkbox logic doesn't work.

Don't hesitate to tell me if the jsfiddle or the question is not enough clear, I will try to reformulate it,

Thanks for the help and have a nice day!

Please sign in or create an account to participate in this conversation.