LoginSignup
260
232

More than 5 years have passed since last update.

Vue.jsで10万件のリストを表示する

Posted at

はじめに

Vue.jsは軽量ですが、数万件のリストを並べるとそりゃ普通につらい。
だから目に見えるとこ以外はdom描いてもらうのやめるってコードです。

デモ

デモ(jsfiddle)

コード

html
<div id="app">
 <div style="overflow:auto;height:170px;"
      @scroll="getScrollParam">
  <ul :style="listStyle">
    <li style="height:17px" 
        v-for="num in displayList">{{num}}</li>
  </ul>
 </div>
</div>
javascript
new Vue({
    el: '#app',
    data: function(){
      return {
        list:list,
        scroll:0,//スクロール量
        scrollMax: (list.length - displayRowNum) * listItemHeight //最大のスクロール量
      }
    },
    computed:{
      displayList:function(){
        //ユーザーの目に映るところだけリストを描画する
        var startIndex = parseInt(this.scroll/listItemHeight,10);
        return this.list.slice(startIndex,startIndex+displayRowNum);
      },
      listStyle:function(){
        //domを並べる代わりにpaddingでダミーの高さを出す
        return {
         'padding-top':this.scroll + 'px',
         'padding-bottom':(this.scrollMax - this.scroll) + 'px',
         'margin':0
        }
      }
    },
    methods:{
        getScrollParam:function(e){
          this.scroll = e.target.scrollTop;
        }
    }
})

おわりに

わかりやすさのために見えてる長さちょうどのリストを表示しましたが、
2,3倍の長さにしたほうがスクロール時にちらつかなくて良いです。
あと実際使う時はクロスブラウザのためにスクロール量や高さの取得に調整が必要です。

260
232
2

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
260
232