在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'
}
}
...