美文网首页
大量数据异步渲染优化(vue)

大量数据异步渲染优化(vue)

作者: 肥羊猪 | 来源:发表于2021-03-24 12:49 被阅读0次

    vue文件:

    <template>
      <ul @scroll="handleScroll($event)">
        <li v-for="(item,id) in list" :key="item.id">
          <div class="item">
            <span>{{item.title}}</span>
            &nbsp;&nbsp;&nbsp;
            <span>{{item.name}}</span>
          </div>
          <div class="item">
            <img :src="'https://oss.itell.club/images/content'+id+'.png'" alt="">
            <span>{{item.content}}</span>
          </div>
        </li>
      </ul>
    
    </template>
    
    <script>
    import common from '@/utils/tools.js'
    export default {
      data() {
        return {
          listData: [],
          page:1,
          size:12
        }
      },
      computed:{
        list:function(){
          return this.listData.slice(0,this.page*this.size)// 每次展示size条数据
        }
      },
      mounted() {
        let temp = []
        for (let i = 1; i <= 10000; i++) {
          temp.push({
            id: i,
            title: 'title' + i,
            name:'name'+i,
            content:'content'+i
          })
        }
        this.listData = temp
      },
      methods:{
        morechange() {
          this.page++// 滚动更多数据
          this.$forceUpdate()
        },
        refresh() {
          this.page = 1// 刷新初始化
          this.$forceUpdate()
        },
        handleScroll(e) {// 滚动函数
          let _this = this
          common.handleScroll(e, function(res) {
            if (res == 'more') {
              _this.morechange()
            } else if (res == 'refresh') {
              _this.refresh()
            }
          })
        },
      }
    }
    </script>
    
    <style lang="css" scoped>
    ul{
      /* 关键高度设置 */
      height:80vh;
      overflow-y:scroll;
      background:#DDD;
    }
    li{
      height:15vh;
    }
    </style>
    
    

    js:

    const common = {}
    common.handleScroll = function(e, callback) {
      let conScrollHeight = e.target.scrollHeight
      let conClientHeight = e.target.clientHeight
      let conScrollTop = e.target.scrollTop
      // console.log(conScrollTop, conClientHeight, conScrollHeight)
      // 刷新或者滚动操作
      let res = conScrollTop + conClientHeight + 1 >= conScrollHeight ? 'more' : (conScrollTop <= 0 ? 'refresh' : false)
      callback(res)
    }
    export default common;
    

    同时 这个地方可以用函数节流和防抖来进一步优化 具体参考:https://www.jianshu.com/p/b1870a66b3d7

    相关文章

      网友评论

          本文标题:大量数据异步渲染优化(vue)

          本文链接:https://www.haomeiwen.com/subject/ylzchltx.html