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)
相关推荐
晚烛14 分钟前
CANN + 物理信息神经网络(PINNs):求解偏微分方程的新范式
javascript·人工智能·flutter·html·零售
小迷糊的学习记录1 小时前
0.1 + 0.2 不等于 0.3
前端·javascript·面试
空&白2 小时前
vue暗黑模式
javascript·vue.js
VT.馒头3 小时前
【力扣】2695. 包装数组
前端·javascript·算法·leetcode·职场和发展·typescript
css趣多多3 小时前
一个UI内置组件el-scrollbar
前端·javascript·vue.js
-凌凌漆-3 小时前
【vue】pinia中的值使用 v-model绑定出现[object Object]
javascript·vue.js·ecmascript
大橙子额5 小时前
【解决报错】Cannot assign to read only property ‘exports‘ of object ‘#<Object>‘
前端·javascript·vue.js
WooaiJava6 小时前
AI 智能助手项目面试技术要点总结(前端部分)
javascript·大模型·html5
LYFlied6 小时前
从 Vue 到 React,再到 React Native:资深前端开发者的平滑过渡指南
vue.js·react native·react.js
Never_Satisfied7 小时前
在JavaScript / HTML中,关于querySelectorAll方法
开发语言·javascript·html