LoginSignup
7
2

More than 3 years have passed since last update.

【Vue初心者向け】並び替え(sort)のサンプルコード

Posted at

Vue.jsで作ったシンプルなサンプルコードです。

対象者は、Vue.jsを始めたところで、色々サンプルコードをいじってみたい人です。

並び替えたい項目のボタンをクリックすると順番に並び替えます。

実際に動作はこちらで確認できます。
並び替え(sort)のサンプルコード

<template>
    <div class="sort_component">
        <p>並び替え</p>
        <ul>
            <li><button @click="sort(0)">id順</button></li>
            <li><button @click="sort(1)">名前順</button></li>
            <li><button @click="sort(2)">年齢順</button></li>
        </ul>
        <div v-for="item in sortItems" :key="item.id">
            id:{{item.id}} 名前:{{item.name}} 年齢:{{item.age}}
        </div>
    </div>
</template>

<script>
export default {
    data(){
        return{
            sortItems:[
                {id:1, name:"taro", age:10},
                {id:2, name:"akane", age:20},
                {id:3, name:"yuki", age:12},
                {id:4, name:"hanako", age:9},
                {id:5, name:"takasi", age:27},
                {id:6, name:"kaori", age:32}
            ]
        }
    },
    methods:{
        sort(index){
            switch(index) {
            case 0:
                this.sortItems.sort(function(a,b){
                    if(a.id < b.id) return -1;
                    if(a.id > b.id) return 1;
                    return 0;
                });
                break;
            case 1:
                this.sortItems.sort(function(a,b){
                    if(a.name < b.name) return -1;
                    if(a.name > b.name) return 1;
                    return 0;
                });
                break;
            case 2:
                this.sortItems.sort(function(a,b){
                    if(a.age < b.age) return -1;
                    if(a.age > b.age) return 1;
                    return 0;
                });
                break;
            default:
            }
        }
    }
}
</script>

<style scoped>

</style>

ポイントは、各ボタンにindexとして数字を振っておいて、switchで分けている所です。並び替えの方法は色々ありますが、今回はシンプルに順番を比較して並び替えてます。
ボタンをクリックしたら並べ替えるのでmethodsでやってますがデータを取得した瞬間に並べ替えたいならwatchとかで使えば入れ替えできます。

宣伝:ブログやっています→ ブログ

7
2
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
7
2