vue2动态滚动表格组件

1.先上图

 2.组件代码

<template>
  <div class="table" @mouseout="start" @mouseover="stop">
    <div class="thead" ref="thead">
      <div v-for="item in th" :style="`width: ${item.width}%`">
        {{ item.label }}
      </div>
    </div>
    <div class="tbody" ref="tbody">
      <div class="tr" v-for="item in td">
        <div class="td" v-for="val in th" :style="`width: ${val.width}%`">{{ item[val.prop] }}</div>
      </div>
    </div>
  </div>
</template>
export default {
  props: {
    th: {
      type: Array,
      default: []
    },
    td: {
      type: Array,
      default: []
    },
    scorll: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      scrollTop: 0
    }
  },
  mounted() {
    if (this.scorll) this.time()
  },
  beforeDestroy() {
    clearInterval(this.myScroll)
  },
  methods: {
    scrollUp() {
      //拿到整个tbody的高度
      let tbody = this.$refs.tbody
      let tbodyHeight = this.$refs.tbody.offsetHeight
      //拿到所有行的高度
      let trs = tbody.children
      let trHeight = trs[0].offsetHeight
      let trsHeight = trHeight * trs.length
      //2者之差就是要滚动多少高度
      let num = trsHeight - tbodyHeight
      if (this.scrollTop > num) {
        this.scrollTop = 0
      } else {
        this.scrollTop++
      }
      tbody.scrollTo(0, this.scrollTop)
    },
    time() {
      this.myScroll = setInterval(this.scrollUp, 100)
    },
    //鼠标移入
    start() {
      clearInterval(this.myScroll)
      this.time()
    },
    //鼠标移出
    stop() {
      clearInterval(this.myScroll)
    }
  }
}
<style lang="less" scoped>
.table {
  width: 100%;
}

.thead {
  width: 100%;
  display: flex;
  justify-content: space-between;
  div {
    text-align: center;
    color: #668979;
    font-weight: 400;
  }
}

.tbody {
  width: 100%;
  height: 500px; //高度必须有
  overflow-y: auto;
  .tr {
    width: 100%;
    height: fit-content;
    box-sizing: border-box;
    display: flex;
    justify-content: space-between;
  }
  .td {
    text-align: center;
    color: #03A55B;
    opacity: 0.89;
  }
}

3.调用组件

<table-component :th="th" :td="data"></table-component>


//表头格式    宽度是百分比
th: [
        { prop: 'number', label: '序号', width: 20 },
        { prop: 'yield', label: '总产量', width: 20 },
      ]
//数据格式
data:[
{number:1, yield: 123},
{number:2, yield: 1234},
]

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值