iview版本: 3.5.0-rc.1
vue版本: 2.6.10
javascript
iview中的table是不能直接占满父容器的,它的 height
属性必须设置成一个固定值。假如直接给table设置style为height:100%
,它的滚动条会丢失。html
可是不少时候咱们须要table占满父容器,须要表头和页脚进行固定,只让中间数据部分进行滚动。vue
在 chrome
中打开 Elements
,能够看到 iview使用了 object
标签。 html中通常只能监听 window
的 resize
事件,而没法直接监听 div
等元素大小改变的,可是有时能够插入一个 object
标签来间接监听 div
大小的改变。它这里是否用了object
来监听大小改变呢?
打开 iview的源码 ,看到它果然是用来监听大小改变的,可是它监听改变后只处理了 width
,没有处理 height
。因此这里咱们能够包装一下 Table,监听它的resize事件,而后动态设置 height属性,来使 Table支持 height:100%
。
java
iview是用的 element-resize-detector
库来监听外层div的改变,而且把将这个库设置为组件的全局变量。因此咱们也可使用这个全局变量来监听外层div大小,而后动态设置 height。git
建立一个 FillTable的组件,用来包装 Table, FillTable.js
的源码以下:github
import { Table } from 'iview'; export default { name: 'fill-table', render(h) { /**传递prop */ const tableProps = {}; for (let prop in Table.props) { tableProps[prop] = this[prop]; } tableProps.height = this.tableHeight; return h(Table, { props: tableProps, ref: 'table', /**传递事件 */ on: this.$listeners, /**传递做用域插槽 */ scopedSlots: this.$scopedSlots, /**传递插槽 */ slot: this.$slot }); }, props: (() => { var props = {}; Object.assign(props, Table.props, { height: { type: Number }, /** 默认占满父容器 */ fill: { type: Boolean, default: true } }); return props; })(), watch: { height: { handler() { this.tableHeight = this.height; } }, immediate: true }, data() { // 自带属性值 return { tableHeight: 0 }; }, methods: { handleIViewTableResize(el) { this.tableHeight = el.offsetHeight; }, getTableRef() { return this.$refs.table; } }, mounted() { if (this.fill) { // this.$nextTick(() => { this.getTableRef().observer.listenTo(this.$el, this.handleIViewTableResize); // }); } /**传递方法 */ for (let method in Table.methods) { this[method] = (...args) => Table.methods[method].apply(this.getTableRef(), args); } }, beforeDestroy() { if (this.fill) { this.getTableRef().observer.removeListener(this.$el, this.handleIViewTableResize); } } };
使用时和iview中的table的属性和方法基本一致,只有如下地方须要注意:chrome
height:100%
的样式。v-bind:height=固定值
,则须要 v-bind:fill="false"
getTableRef
方法,如 this.refs.table.getTableRef()
。<FillTable ref="table" style="width:100%;height:100%" :columns="columns1" :data="data1" :fill="true" > <template #name="{ row }"> <strong>{{ row.name }}--ddd</strong> </template> </FillTable>
因为是侵入性修改,假如iview改了源码,好比将observer的全局字段去除了,则这里就会出错。这时能够直接引用 element-resize-detector
来监听Table的大小改变。app
在线运行: https://meteor199.github.io/my-demo/vue/iview-fill-table/dist/index.html
demo源码:https://github.com/meteor199/my-demo/tree/master/vue/iview-fill-tableiview