美文网首页
vue中el-table高度 动态自适应

vue中el-table高度 动态自适应

作者: 牛会骑自行车 | 来源:发表于2021-12-07 20:22 被阅读0次

之前发那版会报错儿哈哈哈哈哈再来一个妹有问题的~

一个js文件(utils.js)中写一个获取动态高度的公共方法及防抖方法 ↓

function getClientInfo() {
  // 获取用户屏幕高度:减去的130是页面中layout之类固定的高度
  return parseInt(window.innerHeight - 130) || parseInt(document.documentElement.clientHeight - 130) || parseInt(document.body.clientHEight - 130);
}
/**
 * @returns {num: 表格动态高度}
 */
export function getDynamicHeight(ref) {
  // 获取到的实时屏幕高度 - 页面中固定的元素高度
  let height = parseInt(getClientInfo()) - parseInt(window.getComputedStyle(ref).height);
  return {
    height
  };
}

// 防抖
/**
 * @param {Function} func
 * @param {number} wait
 * @param {boolean} immediate
 * @return {*}
 */
export function debounce(func, wait, immediate) {
  let timeout, args, context, timestamp, result

  const later = function () {
    // 据上一次触发时间间隔
    const last = +new Date() - timestamp

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last)
    } else {
      timeout = null
      // 如果设定为immediate===true,因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        result = func.apply(context, args)
        if (!timeout) context = args = null
      }
    }
  }

  return function (...args) {
    context = this
    timestamp = +new Date()
    const callNow = immediate && !timeout
    // 如果延时不存在,重新设定延时
    if (!timeout) timeout = setTimeout(later, wait)
    if (callNow) {
      result = func.apply(context, args)
      context = args = null
    }

    return result
  }
}

在使用动态高度列表的页面中 👇
1.将固定内容的ref名儿写好 ↓

<div class="search-container" ref="searchContainer">

2.el-table的高度设置成动态 ↓

      <el-table
        :data="listData"
        :height="tableHeight"
      >

3.script标签顶部引入需要的方法 ↓

import { getDynamicHeight, debounce } from "@/utils/utils";

4.data中定义tableHeight ↓

data() {
  return {
    tableHeight: 0
  }
}

5.mounted函数中执行的方法 ↓

  mounted() {
    // 初始化给table高度赋值
    this.getHeight();
    // 屏幕resize监听方法
    this.screenMonitor();
  },

6.methods中的方法们 ↓

    screenMonitor() {
      let resize = debounce(() => {
        this.getHeight();
      }, 100);
      // 屏幕resize监听事件:一旦屏幕宽高发生变化,就会执行resize
      window.addEventListener("resize", resize, true);
      // 将屏幕监听事件移除
      // 这步是必须的。离开页面时不移除,再返回,或者进入到别的有相同元素的页面会报错
      // 或者将这里的方法直接写在beforeDestroy函数中也可,不过我感觉这样写更明了些
      this.$once("hook:beforeDestroy", () => {
        window.removeEventListener("resize", resize, true);
      });
    },
    getHeight() {
      // 为什么设置了一个定时器我忘却了。。。。大概因为在获取元素时还没有元素吧哈哈哈哈我真的讲不明白但是得有这个定时器
      setTimeout(() => {
        this.tableHeight = getDynamicHeight(this.$refs.searchContainer).height;
      }, 400);
    },

tada~~~随页面高度变化的动态表格就完成啦

相关文章

网友评论

      本文标题:vue中el-table高度 动态自适应

      本文链接:https://www.haomeiwen.com/subject/lxvaxrtx.html