效果图:
main.vue
<template>
<label for="切换">
'null',全部显示,切换数大于当前数,显示全部,总共:
{{ list.length }}条数据:<br />
当前显示到
<input type="text" name="" id="" v-model="line" @input="change" />行
</label>
<div v-autoHeight="lineHeight" ref="height" class="table">
<table>
<thead>
<tr>
<th>序号</th>
<th>标题</th>
</tr>
</thead>
<tbody>
<tr v-for="item in list" :key="item.id">
<td v-text="item.id"></td>
<td v-text="item.name"></td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import autoHeight from "./components/minHeight.js";
import { ref, toRefs } from "vue";
export default {
directives: {
autoHeight,
},
setup(props) {
let lineHeight = ref(3);
let line = ref(lineHeight.value);
const list = ref([
{ id: 1, name: "23" },
{ id: 2, name: "阿达水电费" },
{ id: 3, name: "asdfasfwe" },
{ id: 4, name: "阿斯顿发" },
{ id: 5, name: "阿斯顿发" },
{ id: 6, name: "asdfasfwe" },
{ id: 7, name: "asdfasfwe" },
{ id: 8, name: "阿斯顿发" },
{ id: 9, name: "asdfasfwe" },
{ id: 10, name: "阿斯顿发" },
{ id: 11, name: "asdfasfwe" },
{ id: 12, name: "阿斯顿发" },
]);
const change = () => {
lineHeight.value = line.value;
console.log(lineHeight.value);
};
return {
line,
list,
lineHeight,
change,
};
},
};
</script>
<style lang="less" scoped>
.table {
width: 100%;
table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
thead {
tr {
th {
font-family: "Times New Roman", Times, serif;
font-size: 18px;
font-weight: 500;
line-height: 40px;
border: 1px solid #eaeef5;
background-color: #eaeef5;
}
}
}
tbody {
tr {
text-align: center;
td {
font-family: "楷体";
font-size: 15px;
border: 1px solid #eaeef5;
line-height: 40px;
word-break: break-all;
}
}
}
}
}
</style>
minHeight.js
function autoHeight(el, binding, vnode) {
// 判断是否全部显示
let allHeight = binding.value
// 最低显示标题
let length = Number(binding.value) != 0 ? Number(binding.value) : 0
// 获取整个表格
let table = el.children[0]
let tabTop = table.children[0].children[0]
let tabBot = table.children[1].children
let minHeight = tabTop.offsetHeight + 1;
// 没有数据直接返回
if (tabBot.length === 0) return
tabBot.forEach((item, index) => {
if (allHeight === 'null') {
minHeight += item.getBoundingClientRect(true).height
} else if (index < length) {
minHeight += item.getBoundingClientRect(true).height
}
});
// 设置样式
el.style.height = minHeight + 'px';
el.style.overflowY = 'auto'
}
export default {
mounted(el, binding, vnode) {
autoHeight(el, binding, vnode)
},
updated(el, binding, vnode) {
autoHeight(el, binding, vnode)
},
}