Solve the adaptive height problem of element table
When writing a company's backend project, we encountered a requirement that the table page cannot have scroll bars, so we must encapsulate a public method to achieve the adaptive height of the table.
Step 1: Implement custom instructions to monitor the height changes of table elements
I use the idea of sealing here. First, create the content in the obSize folder as follows
const map = new WeakMap() // Ob monitorconst ob = new ResizeObserver((entries) => { for (const entry of entries) { // Process the callbacks corresponding to the element const handler = () if (handler) { const box = [0] // Loop and accumulate offsetTop to get the distance from the top of the page let setTop = countTop(, 0) handler({ width: , height: , entry: entry, bodHeight: , setTop: setTop, tableHeight: ( - setTop - 50 - ) > 0 ? '' : - setTop - 72 }) } } }) export function countTop(el, topn) { if () { return countTop(, topn + ) } else { return topn } } export default { inserted(el, binding) { (el) // Listen to the changes in the el element size (el, ) }, unbind(el) { // Cancel the monitoring (el) }, }
Register vue directive in directive folder file
import obSize from './obSize' const install = function (Vue) { //You can put multiple custom commands here ('ob-size', obSize) } if () { (install); // eslint-disable-line } export default install
Introducing directive
import directive from './directive' (directive)
Step 2: Encapsulate mixins
Create content in the mixins folder as follows70Represents the height from the bottom of the page
import { countTop } from '@/directive/obSize' export default { data() { return { tableHeight: 0, } }, methods: { handleSizeChange(e) { = ; }, }, // Listen to showSearch watch: { showSearch(val) { // Get element table element const dome = ('el-table'); let setTop = countTop(dome, 0) = - setTop - 70 }, }, mounted() { // Listen to page size changes ('resize', () => { const dome = ('el-table'); let setTop = countTop(dome, 0) = - setTop - 70 }); }, }
Step 3: Introduce on the page
Introduce import estimateTableHeight from "@/mixins/estimateTableHeight";
export default { mixins: [estimateTableHeight], }
Add v-ob-size="handleSizeChange" on el-table :height="tableHeight"
<el-table v-ob-size="handleSizeChange" :height="tableHeight" v-loading="loading" :data="List" >
The mission is done!
The above is the detailed content of a article to solve the adaptive height problem of vue2 element el-table. For more information about the adaptive height of vue2 element el-table, please pay attention to my other related articles!