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)
相关推荐
宿6745 小时前
vue3-包管理器
前端·vue.js
mayaairi6 小时前
Vue2 生命周期完全指南:从创建到销毁的8个钩子函数
前端·javascript·vue.js
研☆香7 小时前
一个简单的气泡弹窗制作
javascript
大模型丫丫7 小时前
用 TypeScript、NestJS 和 LangGraph 搭建一个可控的 AI Agent
javascript·人工智能·typescript
IMPYLH7 小时前
HTML 的 <pre> 元素
前端·javascript·html
shmily麻瓜小菜鸡8 小时前
JavaScript / TypeScript 易踩坑知识点 —— 异步编程类
开发语言·javascript·typescript
tsumikistep8 小时前
【前端】Vue + Axios 跨域问题实战:7070 代理转发 8080 + 401 报错分析(黑马外卖)
前端·javascript·vue.js
今日无bug10 小时前
从0到1手撕流式输出:Vue3 + Vite 实现 LLM 流式响应全解析
前端·vue.js·vite
默_笙10 小时前
🧀 用户访问一个网站到底经历了什么?全栈部署的"城市观光"指南
前端·javascript
晓天衡宇•评测社区12 小时前
Seedance 2.5 登顶图生视频榜单,Wan 3.0 在游戏与教育场景进入前列
前端·javascript·网络