Vue 自适应高度表格

Vue 自定义指令

你可能会好奇 v-adaptive 是在哪里来的?它是自定义的指令,设置表格高度需要对普通 DOM 元素进行底层操作。Vue 除了核心功能默认内置的指令 (v-model 和 v-show),也允许注册自定义指令,相关 Api 可以查看 官方文档 。

v-adaptive

新建包名src/directive/el-table,创建 adaptive.js 。页面缩放的监听是使用的 element-ui 中的 resize-event,将 addResizeListener 和 removeResizeListener 引入进来。自定义指令要用到的钩子函数:

bind:只调用一次,指令第一次绑定到元素时调用。在这里可以进行一次性的初始化设置。

inserted:被绑定元素插入父节点时调用 (仅保证父节点存在,但不一定已被插入文档中)。

unbind:只调用一次,指令与元素解绑时调用。

componentUpdated:指令所在组件的 VNode 及其子 VNode 全部更新后调用。

adaptive.js代码

复制代码
import { addResizeListener, removeResizeListener } from 'element-ui/src/utils/resize-event'

const doResize = async(el, binding, vnode) => {
  const { componentInstance: $table } = await vnode

  const { value } = binding

  if (!$table.height) {
    throw new Error(`el-$table must set the height. Such as height='100px'`)
  }
  const bottomOffset = (value && value.bottomOffset) || 30

  if (!$table) return

  const height = window.innerHeight - el.getBoundingClientRect().top - bottomOffset
  $table.layout.setHeight(height)
  $table.doLayout()
}

export default {
  bind(el, binding, vnode) {
    el.resizeListener = async() => {
      await doResize(el, binding, vnode)
    }
    addResizeListener(el, el.resizeListener)
    addResizeListener(window.document.body, el.resizeListener)
  },
  async inserted(el, binding, vnode) {
    await doResize(el, binding, vnode)
  },
  async componentUpdated(el, binding, vnode) {
    await doResize(el, binding, vnode)
  },
  unbind(el) {
    removeResizeListener(el, el.resizeListener)
  }
}

接下来,需要将写好的逻辑绑定到 Vue 中,在同一目录下新建 index.js:

复制代码
import adaptive from './adaptive'

const install = function(Vue) {     
    // 绑定v-adaptive指令
    Vue.directive('adaptive', adaptive)
}

if (window.Vue) {
    window['adaptive'] = adaptive  
    // eslint-disable-next-line no-undef 
    Vue.use(install)
}

adaptive.install = install

export default adaptive

全局使用main.js

复制代码
import directive from './directive' // directive
Vue.use(directive)
相关推荐
小小善后师18 分钟前
用 Canvas + AI 实现登录页的 Logo 粒子动画
前端·vue.js
0nirvana026 分钟前
从普通 script 到 ESM:一文搞懂 JavaScript 模块、IIFE 和 window
javascript
wshzd1 小时前
LLM之Agent(104)|DeepSeek-Harness(十三)ReactLoopAgent 总览:kick → turn → step
开发语言·前端·javascript
web打印社区2 小时前
远程打印:WebSocket 与 HTTP 轮询怎么选
前端·vue.js·websocket·网络协议·http·electron·pdf
天天喝旺仔3 小时前
浏览器渲染原理:从解析 HTML/CSS、构建渲染树到重排重绘与首屏优化
前端·javascript·css·性能优化·html
Days20504 小时前
时间胶囊项目正式发布
javascript·gpt·php
朱 欢 庆4 小时前
el-table-v2 虚拟表格组件
前端·javascript·vue.js
OpsEye4 小时前
企业大模型用量成本该如何监控和管控?
javascript·ai编程
杨利杰YJlio4 小时前
ITSK 万能驱动 26V5:新驱动批量更新
前端·javascript·后端
y = xⁿ5 小时前
关于Agent智能体开发
开发语言·前端·javascript