vue3 中 table fix & table height fix

406 阅读1分钟

前言

控制 table 的高度会使用起来更加顺心

table fix

整个页面不滚动,table 的 body 滚动

屏幕录制2022-12-12-11.08.15.gif

const formRef: Ref<HTMLFormElement | null> = ref(null) // form ref
const tableRef: Ref<HTMLFormElement | null> = ref(null) // table ref
const tableMaxHeight = ref(0) // table body 默认值 0

onMounted(() => {
  const appMainDom = document.getElementsByClassName('appMain')[0] // layout 中的 appMain 容器
  const headerDom = tableRef.value?.$el.querySelectorAll(
    '.n-data-table-base-table-header'
  )[0] // table header

  const appMainStyle = window.getComputedStyle(appMainDom)
  const headerStyle = window.getComputedStyle(headerDom)

  tableMaxHeight.value =
    Number.parseFloat(appMainStyle.height) -
    Number.parseFloat(appMainStyle.paddingTop) -
    Number.parseFloat(appMainStyle.paddingBottom) -
    Number.parseFloat(headerStyle.height) -
    formRef.value?.$el.offsetHeight
})

table height fix

整个页面滚动,table 高度等同于容器

屏幕录制2022-12-12-11.13.14.gif

function fix() {
  const appMainDom = document.getElementsByClassName('appMain')[0]
  const headerDom = tableRef.value?.$el.querySelectorAll(
    '.n-data-table-base-table-header'
  )[0]

  const appMainStyle = window.getComputedStyle(appMainDom)
  const headerStyle = window.getComputedStyle(headerDom)

  tableMaxHeight.value =
    Number.parseFloat(appMainStyle.height) -
    Number.parseFloat(appMainStyle.paddingTop) -
    Number.parseFloat(appMainStyle.paddingBottom) -
    Number.parseFloat(headerStyle.height)
}

知识点

vue3 中获取

  1. 常用手法是 ref 绑定元素
const formRef: Ref<HTMLFormElement | null> = ref(null)
formRef.value?.$el.offsetHeight // 元素高度
<n-form ref="formRef">
  ...
</n-form>
  1. document 方式
const appMainDom = document.getElementsByClassName('appMain')[0]
appMainDom.getAttribute('class') // appMain

Number.parseFloat

将字符串转成浮点数,parseFloat 是全局方法。推荐使用 Number.parseFloat 模块化思维

getComputedStyle

window 对象上的方法,得到样式对象

getComputedStyle

总结

  1. 可以根据筛选项来判断需要使用哪种固定方式