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},
]