Home > Software design >  Vue Unchecking isn't removing data from array?
Vue Unchecking isn't removing data from array?

Time:12-12

I have a function that pushes the networkAudience to the array when the checkbox is checked but when I unchecked it the same network Audience get pushed into the array again. Clicking the networkAudience should be removed when I uncheck the box.

How should I change my function so that a networkAudience is removed if it's unchecked?

new Vue({
  el: '#app',
  data: {
    networkAudience: {}
    selected:[]
  },
  methods: {
    netToggle(networkAudience)
        {     
            if(!this.selected.includes(networkAudience)) 
                this.selected.push(networkAudience);
            else 
                this.selected.splice(this.selected.indexOf(networkAudience), 1);
  
        }

  }
});
<div v-for="(networkAudience, index) in networkAudiences" : key="index">
  <tr>
    <input
      
      type="checkbox"
      :checked="selected.includes(networkAudience)"
      @click="netToggle(networkAudience)"
    >
  </tr>
</div>

This should only show one object because I unchecked a box but I end up with two objects. The unchecked box duplicates.

enter image description here

CodePudding user response:

If I understood you correctly , try like following snippet:

new Vue({
  el: '#app',
  data() {
    return {
      networkAudiences: [{id:1, name:'aaa'}, {id:2, name: 'bbb'}, {id:3, name: 'ccc'}],
      networkAudience: {},
      selected: []
    }
  },
  methods: {
    netToggle(networkAudience) {     
      if(!this.selected.includes(networkAudience)) {
        this.selected.push(networkAudience);
      } else {
        this.selected.splice(this.selected.indexOf(networkAudience), 1);
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="(networkAudience, index) in networkAudiences" :key="index">
    <div>
      <label :for="networkAudience.id">{{ networkAudience.name }}</label>
      <input
        
        type="checkbox"
        :id="networkAudience.id"
        :value="networkAudiences[index]"
        @input="netToggle(networkAudience)"
      />
    </div>
  </div>
  {{selected}}
</div>

  • Related