LoginSignup
1
1

More than 3 years have passed since last update.

Vue.js v-forの使い方 シャッフルをする lodash

Last updated at Posted at 2020-07-15

lodashを使用したシャッフルボタンの実装

参考記事:https://www.youtube.com/watch?v=S0b1ZBIooyY&list=PLh6V6_7fbbo-SZYHHBVFstU2tp0dDZMAW&index=7

lodash:https://lodash.com/
(lodashはシャッフルを簡単にするために使用している。)

前回学んだ配列をv-forで表示させるものの続き
前回記事
Vue.js v-forの使い方 配列とオブジェクト比較

ボタンを押すと配列の並びが変化するようにした。
コード


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .flip-list-move{
            /* このflip-listはtransition-groupのname属性を差す。-moveはここが動いた時にこのcssを着火させるという意味 */
            transition:transform .5s;
        }
    </style>
</head>
<body>
    <h1>Vueの練習:v-for</h1>

<!-- オブジェクトの配列のv-for -->
<div id="app2">
    <button v-on:click='shuffle'>シャッフル</button>
    <transition-group name='flip-list' tag='ul'>
        <!-- transition-groupタグで囲う時はtagで指定したulタグの開始タグは不要 -->
        <li v-for='item in items' v-bind:key='item.name'>{{item.name}}</li>
        <!-- transition-groupをかける為にv-bind:keyの設定が必要 -->
        <!-- v-bind:key  :keyに省略も可能 -->
    </transition-group>        
    </ul>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.19/lodash.min.js"></script>
<script>

// オブジェクトの配列のv-for
new Vue({
    el:'#app2',
    data:{
        items:[
            {name:'北海道'},
            {name:'青森県'},
            {name:'岩手県'},
            {name:'宮城県'},
            {name:'秋田県'},
            {name:'山形県'}
            ]
    },
    methods: {
        shuffle:function(){
            this.items = _.shuffle(this.items);//「_.」はlodashを使うときの宣言。参考:https://lodash.com/
        }
    },
})


</script>
</body>
</html>

結果
スクリーンショット 2020-07-16 6.54.01.png
これが
ボタンを押すと

スクリーンショット 2020-07-16 6.54.15.png
このように順番が変わる

ポイント


 <transition-group name='flip-list' tag='ul'>
        <li v-for='item in items' v-bind:key='item.name'>{{item.name}}</li>
 </transition-group>        

transition-groupで前回書いていたulタグを囲む
この時、ulの開始タグを消し、transition-groupの開始タグ内でtag='ul'を設定する点注意

属性keyの扱い

v-bind:keyを設定することでシャッフルする対象を指定している。
この辺りの扱いがまだ理解できていない。
公式ドキュメントを貼っておく。今後理解できるようにしたい。
https://jp.vuejs.org/v2/api/#key

その他ポイントはコード内のコメントに記載
1
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
1
1