LoginSignup
0
1

More than 3 years have passed since last update.

Vue.jsでテーブルを並び替え

Last updated at Posted at 2021-04-26

はじめに

Vue.jsでソートはどうやるのか気になったので備忘録として。

環境設定

今回はCodePenを使って実装します。またテーブルのデータはjsonplaceholderからaxiosを使って取得して使用します。
Vue.jsは2.6.11を使用しています。

1619434240443.png

CodePenのセッティングでvue.jsとaxiosを読み込みます。

See the Pen Vue.js vue-sort by morioka (@rm5912) on CodePen.

HTML
<div id="app">
  <h1>{{ message }}</h1>
  <h2> {{ sort_key }}: {{ sort_asc ? '昇順' : '降順'}}</h2>
  <table>
    <thead>
      <tr>
        #v-onディレクティブのクリックイベントでv-bindディレクティブのaddClassを発火してます。
        <th @click="sortBy('name') " :class="addClass('name')">Name</th>
        <th @click="sortBy('email')" :class="addClass('email')">Email</th>
        <th @click="sortBy('website')" :class="addClass('website')">Website</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="user in sort_users" :key="user.id">
        <td>{{ user.name }}</td>
        <td>{{ user.email}}</td>
        <td>{{ user.website }}</td>
      </tr>
    </tbody>
  </table>
</div>
CSS
table {
  border-collapse: collapse;
  width: 100%
}
td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
th {
  color:white;
  background-color: #1E90EF;
}

.asc::after {
  content: "↓"
}

.desc::after {
  content: "↑"
}
JavaScript
new Vue({
  el: '#app',
  data: {
    message: 'Sort Column IN Table',
    users: [],
    sort_key: "",
    sort_asc: true
  },
  mounted(){
    axios.get('https://jsonplaceholder.typicode.com/users')
    .then(response => this.users = response.data)
  },
  methods: {
    sortBy(key) {
      this.sort_key === key
      ? (this.sort_asc = !this.sort_asc)
      : (this.sort_asc = true)
      this.sort_key = key
    },
    addClass(key) {
      return {
        asc: this.sort_key === key && this.sort_asc,
        desc: this.sort_key === key && !this.sort_asc
      }
    }
  },
  computed: {
    sort_users() {
      if(this.sort_key != "") {
        let set = 1;
        this.sort_asc ? (set = 1) : (set = -1)
        this.users.sort((a, b) => {
          if (a[this.sort_key] < b[this.sort_key]) return -1 * set;
          if (a[this.sort_key] > b[this.sort_key]) return 1 * set;
          return 0;
        })
        return this.users
      } else {
        return this.users
                        }
    }
  }
})

参考サイト
vue.jsでテーブルの列をソート(並べ替え)する方法

0
1
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
0
1