8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Vueで行が選択可能なテーブルを作る

Last updated at Posted at 2020-09-13

作るもの

こんな感じのカラムを選択できるようなテーブルを作ります。
table.gif

<template>
  <table>
    <thead>
      <th>
        <label class="form-checkbox">
          <input type="checkbox" v-model="isSelectAll" @click="select">
        </label>
      </th>
      <th>ID</th>
      <th>ユーザー名</th>
      <th>画像</th>
    <th>作成日</th>
    </thead>
    <tbody>
      <tr v-for="user of users" :key="user.id">
        <th>
          <input type="checkbox" :value="user" v-model="selected">
        </th>
        <td>{{ user.id }}</td>
        <td>{{ user.name }}</td>
        <td>{{ user.image }}</td>
        <td>{{ user.date}}</td>
      </tr>

    </tbody>
  </table>
</template>

<script>
export default {
  data() {
    return {
      users: [
        { id: 1, name: 'jhin', image: 'https://image.test.com', date: '2020/09/10' },
        { id: 2, name: 'ahri', image: 'https://image.test.com', date: '2020/09/11' },
        { id: 3, name: 'yasuo', image: 'https://image.test.com', date: '2020/09/12' },
      ],
      selected: [],
      isSelectAll: false,
    };
  },
  methods: {
    select() {
      this.selected = [];
      if (!this.isSelectedAll) {
        for(let i in this.item) {
          this.selected.push(this.items[i].id);
        }
      }
    }
  },
};
</script>

チェックボックスのv-modelに配列を指定することがポイント。

チェックが入ると:valueで指定したuserオブジェクトが配列のselectedに挿入されます。

console.log(this.selected)
/*
 チェックされたカラムの情報が配列に挿入される
  [
   { id: 1, name: 'jhin', image: 'https://image.test.com', date: '2020/09/10' },
  ],
*/

非常に簡単。

8
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?