目的就是對a-table進行二次封裝,可是在如何顯示a-table的slot時遇到了問題,本來想法是在a-table內把$slots都渲染,指望在使用該組件時能正確渲染,然而。。。並不會正確渲染this
<template> <a-table bordered :scroll="{ x: scrollX, y: 600 }" v-bind="{...$attrs, ...$props, ...{dataSource: body, columns: header}}" :loading="loadingObj" v-on="listeners" > <template v-for="(val, slot) in $slots" :slot="slot">{{ this.$slots[slot] }}</template> </a-table> </template>
後來,在某個寫法裏找到了a-table有scopedSlots這個參數,可是在template裏直接賦值也不行,以下spa
<a-table bordered :scroll="{ x: scrollX, y: 600 }" v-bind="{...$attrs, ...$props, ...{dataSource: body, columns: header}}" :loading="loadingObj" v-on="listeners" :scopedSlots="$scopedSlots" >
組件不採用template寫,用render()
則變成:code
render () { const on = { ...this.$listeners } const props = { ...this.$attrs, ...this.$props, ...{ dataSource: this.body, columns: this.header }} const table = ( <a-table bordered props={props} scopedSlots={ this.$scopedSlots } on={on}> </a-table> ) return ( <div class="dc-table"> { table } </div> ) }, methods: () { }
重點在於scopedSlots={ this.$scopedSlots }, 這樣在使用組件的外部直接寫slot就能夠正常渲染orm
<dc-table ref="table" :columns="header" :dataSource="body" :loading="loading" :pagination="pagination" @change="handleTableChange" class="table-fit" > // 這裏是表頭的渲染,下面會講到 <template v-for="title in headerSlots" :slot="'$' + title"> <span :key="title"> <a-tooltip placement="right" trigger="click"> <template slot="title">{{ getHeaderTarget(title).remark }}</template>{{ getHeaderTarget(title).title }}<a-icon type="info-circle"/> </a-tooltip> </span> </template> // 這裏渲染列數據 <template v-for="(item, index) in DECIMAL_PARAMS" :slot="item" slot-scope="text"> <span :key="index"> <span>{{ text | NumberFixed | NumberFormat }}</span> </span> </template> </dc-table>
以下表格數據本來是數據,渲染成逢三斷一,並2位小數
this.$scopedSlots數據格式:
在header中爲scopedSlots: {customRender: 'consumption'} 格式blog
仍是同一個表格,要求表頭有提示信息,因此我在表頭也作了slots渲染了a-tooltip顯示提示信息ip
此時header格式爲[{scopedSlots: {customRender: 'consumption', title: '$consumption'} }]ci
表頭渲染設置scopedSlots裏title字段,名字自定義rem
此時的this.$scopedSlots也有$consumption表頭slot字段,可是並不能正常渲染出來
可是發現this.$slots裏有且只有表頭的slot
此時我以爲,我應該把$slots的內容渲染在a-table裏,則get
render () { const on = { ...this.$listeners } const props = { ...this.$attrs, ...this.$props, ...{ dataSource: this.body, columns: this.header }} // slots循環 const slots = Object.keys(this.$slots).map(slot => { return ( <template slot={slot}>{ this.$slots[slot] }</template> ) }) const table = ( <a-table bordered props={props} scopedSlots={ this.$scopedSlots } on={on}> {slots} // 放這裏 </a-table> ) return ( <div class="dc-table"> { table } </div> ) },
大功告成it