element表格高度隨瀏覽器高度變化

在vue文件中,我們需要給el-table組件綁定一個refs,這樣我們就可以通過this.$refs.table1獲取到綁定的dom元素

<el-table ref="table1" :height="tableHeight" :data="tableData">
...
</el-table>

新建tools文件,在文件中暴露一個tableHeight函數(shù),如下所示

export function tableHeight(obj) {
  return new Promise(resolve => {
    var height = window.innerHeight - obj.$refs.table1.$el.offsetTop - 52 - 80 - 50
    resolve(height)
  })
}

減去的52、80、50分別為底部的分頁,表格搜索條件,和面包屑導(dǎo)航的高度
我們在需要的頁面上引入該函數(shù),并在頁面mounted時獲取返回的高度,并給window對象添加事件監(jiān)聽函數(shù)onresize,此時綁定的函數(shù)不能放到created()鉤子函數(shù)中,因為此時document還沒有生成,我們默認將表格高度設(shè)置成100,調(diào)用tableHeight函數(shù)時將vue對象的引用傳入進去,方便獲取到表格的dom元素對象,

import { tableHeight } from '@/utils/tools'
data(){
  return { tableHeight: 100 }
}
mounted(){
  tableHeight(this).then(res => {
      this.tableHeight = res
      var that = this
      window.onresize = () => {
        tableHeight(that).then(res2 => {
          that.tableHeight = res2
        })
      }
    })
}

這樣寫完了之后,我們會發(fā)現(xiàn)跳轉(zhuǎn)到別的頁面上時,會重復(fù)觸發(fā)綁定的window.onresize實踐,故我們需要在頁面關(guān)閉的beforeDestory鉤子函數(shù)中結(jié)束該監(jiān)聽

beforeDestroy() {
    window.onresize = null
  }

到這里就可以實現(xiàn)該效果了,我們將以上代碼封裝,使用mixin引入,則不用每個頁面都寫一次以上代碼,只是需要給table添加ref='table1',data中添加tableHeight,:height="tableHeight"
以下是封裝的文件:

import { tableHeight } from '@/utils/tools'
export default {
  mounted() {
    this.reqList()
    tableHeight(this).then(res => {
      this.tableHeight = res
      var that = this
      window.onresize = () => {
        tableHeight(that).then(res2 => {
          that.tableHeight = res2
        })
      }
    })
  },
  beforeDestroy() {
    window.onresize = null
  }
}

在頁面中按如下方式引入:

import resizeTable from '@/utils/resizeTable'
export default {
  name: 'Index',
  mixins: [resizeTable],
...
}

我們還可以在其中添加表格的樣式:

...
methods: {
    headerStyles() {
      return 'headerStyle'
    },
    cellStyles() {
      return 'cellStyle'
    }
  }
...
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容