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)
相关推荐
bai2733 小时前
日志里的 [Object] 不是空对象:console.log 默认只展开两层,console.dir 也一样
javascript·后端
狗头大军之江苏分军3 小时前
《潮水漫过十七岁》 补一下,运动会
前端·javascript·后端
狗头大军之江苏分军3 小时前
《潮水漫过十七岁》书都带回去
前端·javascript·后端
计算机毕设定制辅导-无忧学长3 小时前
《基于SpringBoot的肩周炎健康管理系统设计与实现》
java·vue.js·spring boot·mysql·肩周炎健康管理系统
map_3d_vis4 小时前
控制百度地图视野:setCenter、setZoom、panTo、flyTo 和 setViewport
前端·javascript·地图·百度地图
snow@li21 小时前
前端:导入EXCEL并解析文件内容,demo
前端·javascript·vue.js
RuoyiOffice1 天前
Flowable只是起点:一套OA背后的单据、资源与协作设计
java·vue.js·spring boot·flowable·企业管理·oa·ruoyi office
夕水1 天前
一个小小的颜色选择器,差点让我开发出一个组件库来
前端·javascript·typescript
时间的情敌1 天前
Three.js 射线拾取进阶:hover 高亮、点击弹窗、多物体过滤、穿透拾取
开发语言·javascript·three.js
光影少年1 天前
ts全栈开发
javascript·后端·typescript·node.js·c5全栈