[Vuejs]-How to select All checkboxes based on condition with Vue.js

0👍

You might want to use click event on a element:

<a href="javascript:void(0);" @click="selectAllHandler" class="deleteMessages">All,</a>

and in javascript code:

methods: {
   selectAllHandler() {
     if (this.selected.length) {
       this.selected = []
     } else {
       this.selected = this.messages.map(item => item.id);
     }
   }

}

0👍

Your Javascript:

new Vue({
el: "#app",
data: {
selected: [],

messages: [{
    id: 1,
    text: "Learn JavaScript",
    status: 'read'
  },
  {
    id: 2,
    text: "Learn Vue",
    status: 'unread'
  },
  {
    id: 3,
    text: "Play around in JSFiddle",
    status: 'read'
  },
  {
    id: 4,
    text: "Build something awesome",
    status: 'unread'
  }
]
},
methods: {
  selectAll() {
      this.selected = this.messages.map((message) => message.id); 
  }
}
})

Your HTML:

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

<div id="app">
  <h2>Message App:</h2>
  <table class="table">
<a href="javascript:void(0);" @click.prevent="selectAll" class="deleteMessages">All,</a>
<a href="javascript:void(0);">Read,</a>
<a href="javascript:void(0);">Unread,</a>

<thead>
  <tr>
    <th><input type="checkbox" v-model="selectAll"></th>
    <th>Status</th>
    <th>Message</th>
  </tr>
</thead>
<tbody>
  <tr v-for="(item,index) in messages">
    <td><input type="checkbox" v-model="selected" :value="item.id"></td>
    <td>{{ item.status }}</td>
    <td>{{ item.text }}</td>
  </tr>
</tbody>

Leave a comment