当前位置 主页 > 网站技术 > 代码类 >

    Vue.js 无限滚动列表性能优化方案(2)

    栏目:代码类 时间:2019-12-02 18:05

    <template>
     <virtual-scroller class="virtual-list" ...></virtual-scroller>
    </template>
    
    <style>
    .virtual-list ul {
     list-style: none;
    }
    </style>

    或者也可以用scoped 样式,用 /deep/选择器:

    <style scoped>
    .virtual-list /deep/ ul {
     list-style: none;
    }
    </style>
    
    
    
    

    案例二: VirtualTable

    类似 VirtualList,我们再看一个表格组件VirtualTable: VirtualTable.vue:

    <template>
     <virtual-scroller :items="items" item-height="40" content-tag="table">
      <template slot-scope="props">
       <tr :key="props.itemKey">
        <td>{{props.item.age}}</td>
        <td>{{props.item.name}}</td>
        <td>{{props.item.company}}</td>
       </tr>
      </template>
     </virtual-scroller>
    </template>
    
    <script>
    import items from "./data.json";
    
    export default {
     data: () => ({ items })
    };
    </script>

    这里有个小问题,我们需要增加一个 <thead>标签,用于显示列名: Age, Name 和 Company

    幸好 virtual-scroller 支持 slot,可以定制各部分内容:

    <main>
     <slot name="before-container"></slot>
     <container>
      <slot name="before-content"></slot>
      <content>
       <!-- Your items here -->
      </content>
      <slot name="after-content"></slot>
     </container>
     <slot name="after-container"></slot>
    </main>

    这些 slot 都可以放置自定义内容。container 会被 container-tag 属性值替换,默认是div,content 被 content-tag 值替换。

    这里用 before-content slot 加一个thead 就行了:

    <template>
     <virtual-scroller
      :items="items"
      item-height="40"
      container-tag="table"
      content-tag="tbody"
      >
       <thead slot="before-content">
        <tr>
         <td>Age</td>
         <td>Name</td>
         <td>Company</td>
        </tr>
       </thead>
       <template slot-scope="props">
        <tr :key="props.itemKey">
         <td>{{props.item.age}}</td>
         <td>{{props.item.name}}</td>
         <td>{{props.item.company}}</td>
        </tr>
       </template>
     </virtual-scroller>
    </template>

    请注意,我们把content-tag="table" 改成了content-tag="tbody",因为我们设置了container-tag="table",这是为了构造table 标签的常规结构。

    如果要加一个 tfoot,应该知道怎么做了吧。

    总结

    我们了解了无限滚动列表的性能优化原理,以及利用vue-virtual-scroller Vue 插件创建了 VirtualList 和  VirtualTable 组件。如果用它们来展示前面生成的 5000 条数据,应该可以比较流畅地渲染和滚动了。更多用法可以参考 vue-virtual-scroller 文档 。

    文章涉及的源码 戳这里。

    以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持IIS7站长之家。