案例 | iview中Table:拖拽適配列、自定義固定列、合并行

文 / 景朝霞
來源公號 / 朝霞的光影筆記
ID / zhaoxiajingjing

????點個贊,讓我知道你來過~????


0 / 更新Table

"iview": "2.13.0",對比最新版本的iview:4.1.3中的Table功能,獲取最新功能:拖拽、合并行等。

【PS:由于一些原因不能統一升級整個iview,我動了源碼這很不好,望大佬們不吝賜教更好的方案~】

1 / Table的拖拽適配列

table.vue文件中handleResize方法里實現了:

不設置列的屬性width,而是設置屬性maxWidthminWidth用來適配在拖拽時表格產生的留白的適配,會把留白的寬度平均分配給適配列。

其中,最后呈現的寬度不會比最小寬還小,不會比最大寬度還大。

(1)拖拽設置邊界值

為了使拖拽后的表格不會無限制的寬,也不會特別窄,設置邊界值:

table.vue

minColumnWidth:{
    type:Number,
    default:50
},
maxColumnWidth:{
    type:Number,
    default:560
}

table-head.vue

const columnWidth = _width < this.minColumnWidth ? this.minColumnWidth : (_width > this.maxColumnWidth ? this.maxColumnWidth : _width);
(2)可拖拽范圍加寬

把鼠標可拖拽的范圍放寬:

if (rect.width > 12 && rect.right - event.pageX < 8) 
// 把判斷條件的8改為16

table.less

.@{table-prefix-cls} {
    &-header{
        &-resizable{
            width: 20px; // 把原來的10px更新為20px
        }
    }
}

2 / Table的自定義固定列

公號ID:zhaoxiajiingjing

△圖12.1:用戶可以自己配置固定列

公號:朝霞的光影筆記

△圖12.2:固定后的結果

【PS:實現此功能,請原諒我修改了源碼】

在列上添加屬性freezable:true表示允許用戶自己設置固定列,其代碼里面操作的依舊是列的屬性fixed實現效果。

(1)新增泡泡文件freeze-poptip.vue
<template>
    <!-- 2020年3月10日10:01:50 可以凍結 -->
    <Poptip
            v-model="showFlag"
            popper-class="ivu-table-popper "
            trigger="hover"
            placement="top" :transfer="true">
        <span :class="[prefixCls + '-freeze']">
            <Icon type="loudou" ></Icon>
        </span>
        <div slot="content" :class="[prefixCls + '-freeze-list']">
            <slot name="freezeContent"></slot>
        </div>
    </Poptip>
</template>
<script>
    import Poptip from '../poptip/poptip.vue';

    export default {
        components: { Poptip },
        props:{
            prefixCls: String,
            show:{
                type:Boolean
            },
            hide:{
                type:Boolean
            }
        },
        watch:{
            hide(newFlag, oldFlag){
                if(newFlag === false) {
                    this.showFlag = false;
                }
            }
        },
        data() {
            return {
                showFlag:this.show
            };
        }
    }
</script>
(2)在表頭添加凍結提示泡泡table-head.vue

import FreezePoptip from './freeze-poptip.vue';

<FreezePoptip v-if="column.freezable"
    :show="getColumn(rowIndex, index)._freezeVisible"
              :prefixCls="prefixCls"
              :hide="getColumn(rowIndex, index)._freezeVisiblePoptip"
>
    <template slot="freezeContent">
        <ul :class="[prefixCls + '-freeze-list-single']">
            <li :class="[prefixCls + '-filter-select-item']"
                @click="handleFreezable(getColumn(rowIndex, index)._index, 'left')">
                <Button type="text" :class="[prefixCls + '-freeze-btn']"
                          :disabled="column.fixed === 'left'" >左側凍結</Button>
            </li>
            <li :class="[prefixCls + '-filter-select-item']"
                @click="handleFreezable(getColumn(rowIndex, index)._index, 'right')">
                <Button type="text" :class="[prefixCls + '-freeze-btn']"
                          :disabled="column.fixed === 'right'">右側凍結</Button>
            </li>
            <li :class="[prefixCls + '-filter-select-item']"
                @click="handleFreezable(getColumn(rowIndex, index)._index, '')">
                <Button type="text" :class="[prefixCls + '-freeze-btn']"
                          :disabled="(typeof column.fixed === 'string' && column.fixed.length === 0) || typeof column.fixed === 'undefined'" >還原</Button>
            </li>
        </ul>
    </template>
</FreezePoptip>

添加點擊方法

// 2020年3月10日10:08:28 凍結
handleFreezable(index, type){
    const column = this.columns.find(item => item._index === index);
    const _index = column._index;
    this.$parent.handleFreezable(_index, type);
},
(3)修改table.vue
handleFreezable(_index, type){
    const index = this.GetOriginalIndex(_index);
    const key = this.cloneColumns[index].key;
    this.cloneColumns[index]._freezeVisiblePoptip = false;
    this.$emit('on-freeze-change', {
        column:JSON.parse(JSON.stringify(this.allColumns[this.cloneColumns[index]._index])),
        key,
        fixed:type
    });

},
 makeColumns (cols) {
     //....CODE
     let hasFreezable = columns.some(col => col.freezable===true);
     let hasResizable = columns.some(col => col.resizable===true);
     columns.forEach((column, index) => {
         //...CODE
         (hasFreezable || hasResizable ) && (column.width = parseInt(column.width));
         //...CODE
     });
     //....CODE
 }
(4)應用

應用的代碼在文末

3 / Table的合并行

(1)閱讀iview的源碼

根據iview給出的例子,只需要把合并的規則傳入到組件內即可

https://www.iviewui.com/components/table#H/LHB

公號ID:zhaoxiajingjing

△圖12.3:iview的Table合并行的例子

table-body.vue在這里可以學習一下,如何判斷一個方法的返回值是數組還是對象

getSpan (row, column, rowIndex, columnIndex) {
    // 拿到傳過來的方法 spanMethod
    const fn = this.$parent.spanMethod;
    // 是function類型的才可以
    if (typeof fn === 'function') {
        // 調用該方法,并把返回值結果賦值給變量result
        const result = fn({
            row,
            column,
            rowIndex,
            columnIndex
        });
        // 設置初始值
        let rowspan = 1;
        let colspan = 1;
        if (Array.isArray(result)) { 
            // 返回結果值是數組
            rowspan = result[0];
            colspan = result[1];
        } else if (typeof result === 'object') {  
            // 返回結果值是對象
            rowspan = result.rowspan;
            colspan = result.colspan;
        }
        return {
            rowspan,
            colspan
        };
    } else { // 否則:{}
        return {};
    }
},

(1)判斷是否為函數typeof fn === 'function'

(2)判斷是否為數組Array.isArray(result)

(3)判斷是否為對象typeof result === 'object'【僅限于此處約定的返回值是一個對象或者一個數組】

let fn = function (){
    return [];
};
if (typeof fn === 'function'){ // (1)
    const result = fn();
    if (Array.isArray(result)) { // (2)
        // ...something
    } else if (typeof result === 'object') { //(3)
        // ...something
    }
}

可以看到它的表格數據data5是一條一條寫的。

對于我們想要的數據格式如下,那就需要處理一下了,具體方法見文末

[
    {
        "teacher":"教師1",
        "course":"語文",
        "studentList":[
            {
                "student":"學生1"
            },
            {
                "student":"學生2"
            }
        ]
    }
]
(2)鼠標移入的樣式
公號:朝霞的光影筆記

△圖12.4:鼠標移入的樣式

思路:在設置合并行的時候,給一個統一的標識符,在鼠標移入后,把帶有該標識符的都加上移入的樣式

【PS:大佬們打臉輕一些,請不吝賜教更好的方案】

公號:朝霞的光影筆記

△圖12.5:給tr加上行標識

rowClasses (_index) {
    // ...CODE
    let {rowspanHoverFlag} = objData;
    
    if(rowspanHoverFlag && objData){
        for (let rowIndex in this.objData) {
            let row = this.objData[rowIndex];
            if(row.rowspanHoverFlag === rowspanHoverFlag && this.$parent.$el) {
                let el = this.$parent.$el.querySelector(`.myhoverindex-${rowIndex}`);
    
                let _class = objData._isHover ?
                    ( `myhoverindex-${rowIndex} ${this.prefixCls}-row ${this.rowClsName(rowIndex)} ${this.prefixCls}-row-highlight ${this.prefixCls}-row-hover`)
                    : (`myhoverindex-${rowIndex} ${this.prefixCls}-row ${this.rowClsName(rowIndex)}`);
    
                (el!==null && el.setAttribute) && el.setAttribute('class',_class);
            }
        }
    }
    // ...CODE
}

4 / 應用

PS:自定義凍結是修改的源碼,如需要該功能,請自行貼上面介紹的代碼

PS:我動了源碼這很不好,望大佬不吝賜教更好的方案

公號ID:zhaoxiajingjing

【你可能感興趣】

  1. 題目 | let和var的區別(一、二)
  2. 圖解 | let和var的區別(一、二)
  3. 題目 | 帶VAR和不帶VAR的區別
  4. 圖解 | 帶VAR和不帶VAR的區別
  5. 總結 | LET和VAR區別(三、四)
  6. 圖解 | 作用域和作用域鏈
  7. 練習題 | 作用域和作用域鏈
  8. 圖解 | 理解閉包
  9. 案例 | 閉包作用:保護和保存
<template>
    <Table
                border
                ref="selection"
                :columns="columns3"
                :data="data3"
                :span-method="handleSpan"
                @on-freeze-change="onFreezeChange"

        ></Table>
</template>
<script>

    export default {

        data() {
            return {
                columns3:[
                    {
                        title:'教師',
                        key:'teacher',
                        resizable:true,
                        freezable:true,
                        width:100
                    },
                    {
                        title:'教師編號',
                        key:'teacherCode',
                        resizable:true,
                        freezable:true,
                        width:120
                    },
                    {
                        title:'課程',
                        key:'course',
                        resizable:true,
                        freezable:true,
                        width:120
                    },
                    {
                        title:'學生',
                        key:'student',
                        rowRelation:'many',
                        resizable:true,
                        freezable:true,
                        width:100
                    },
                    {
                        title:'學號',
                        key:'studentCode',
                        rowRelation:'many',
                        resizable:true,
                        width:120
                    },
                    {
                        title:'成績',
                        key:'score',
                        rowRelation:'many',
                        resizable:true,
                        freezable:true,
                        width:100
                    },
                    {
                        title:'批語',
                        key:'explain',
                        rowRelation:'many',
                        freezable:true,
                        minWidth:100
                    }
                ],
                data3:[],
                tableDataArr3:[
                    {
                        "id":1,
                        "teacher":"Name 1",
                        "teacherCode":"Teacher-1",
                        "course":"語文",
                        "studentList":[
                            {
                                "studentCode":"2020001",
                                "student":"學生1",
                                "score":"A",
                                "explain":""
                            },
                            {
                                "studentCode":"2020002",
                                "student":"學生2",
                                "score":"B",
                                "explain":""
                            },
                            {
                                "studentCode":"2020003",
                                "student":"學生3",
                                "score":"B",
                                "explain":""
                            },
                            {
                                "studentCode":"2020004",
                                "student":"學生4",
                                "score":"A",
                                "explain":""
                            }
                        ]
                    },
                    {
                        "id":2,
                        "teacher":"Name 2",
                        "teacherCode":"Teacher-2",
                        "course":"物理",
                        "studentList":[
                            {
                                "studentCode":"2020001",
                                "student":"學生1",
                                "score":"B",
                                "explain":""
                            },
                            {
                                "studentCode":"2020002",
                                "student":"學生2",
                                "score":"B",
                                "explain":""
                            },
                            {
                                "studentCode":"2020003",
                                "student":"學生3",
                                "score":"B",
                                "explain":""
                            }
                        ]
                    },
                    {
                        "id":3,
                        "teacher":"Name 3",
                        "teacherCode":"Teacher-3",
                        "course":"歷史",
                        "studentList":[
                            {
                                "studentCode":"2020003",
                                "student":"學生3",
                                "score":"A",
                                "explain":""
                            },
                            {
                                "studentCode":"2020004",
                                "student":"學生4",
                                "score":"A",
                                "explain":""
                            }
                        ]
                    },
                    {
                        "id":4,
                        "teacher":"Name 4",
                        "teacherCode":"Teacher-4",
                        "course":"美術",
                        "studentList":[
                            {
                                "studentCode":"2020004",
                                "student":"學生4",
                                "score":"A",
                                "explain":""
                            }
                        ]
                    }
                ],
            };
        },
        mounted() {
            setTimeout(() => {
                this.data3 = this.data2TdRowspan({tableData:this.tableDataArr3, rowspanList:'studentList'});
            }, 300);
        },
        methods: {
            onFreezeChange({column = {}, key = '', fixed = ''} = {}) {
                this.columns3 = this.columns3.map((col, index) =>{
                    if (col.key === key) {
                        col['fixed'] = fixed;
                    }
                    return col;
                });
            },
            /**
             * 2020年4月2日09:53:02 by jing_zhaoxia@sina.com
             * @param arr 需要處理的數據數組
             * @param rowspanList 合并行的數組
             * @param rowspanHoverFlag 作為鼠標滑入的行的標記
             * @returns {*} [Array] 將處理好的數據返回去
             */
            data2TdRowspan(params){
                let json = {};

                if (Array.isArray(params)) {
                    json.tableData = params;
                } else if(Object.prototype.toString.call(params) === '[object Object]'){
                    json = params;
                }

                let {tableData:arr = [], rowspanList = 'studentList', rowspanHoverFlag='id'} = json;

                return arr.map((row, index) =>{
                    let rowspanArr = row[rowspanList];
                    let rowspan = rowspanArr.length;

                    return rowspanArr.map((sRow, sIndex) => {
                        sIndex === 0 ? row.rowspan = rowspan : (row.rowspan = 0, row._rowspan = rowspan);

                        sRow.rowspanHoverFlag = row[rowspanHoverFlag];

                        delete row[rowspanList];

                        return { ...sRow, ...row};
                    });
                }).flat(Infinity);
            },
            handleSpan({row:{rowspan}, column:{rowRelation='', isExtended=false}}) {
                return rowRelation !== 'many' ? {rowspan} : {};
            }
        }
    };
</script>
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容