首页 > 解决方案 > 制表符:是否可以为每一行添加具有计算值的自定义列?

问题描述

是否可以为每一行添加具有计算值的自定义列?因此,如果 col 1 的值为“3”而 col 2 的值为“5”,那么我想要动态 col 3 的总和值为 8。

我正在使用 Vue Tabulator。这是我的 Table.vue 组件。

<template>
    <div v-if="tabledata" class="w-full p-3 border border-gray-200 shadow-xl rounded-lg  mt-10">
        <VueTabulator id="usersData" v-model="tabledata" :options="options" />
    </div>
</template>
<script>
export default {
    data(){
        return{
            tabledata: [
                {
                    "name": "Hron",
                    "lvl2": 5,
                    "lvl3": 0,
                    "score": 5
                },
                {
                    "name": "Zhr",
                    "lvl2": 2,
                    "lvl3": 1,
                    "score": null
                },
                {
                    "name": "Mang",
                    "lvl2": 4,
                    "lvl3": 1,
                    "score": null
                }
            ],
            options: {
                layout:"fitColumns",
                columns: [
                    {title:"S#", formatter:"rownum", width:70, align:"center", responsive:3},
                    {title:"Name", field:"name", minWidth:150},
                    {title:"Lvl 2", field:"lvl2", sorter:"number", align:"center", formatter:"money", formatterParams:{precision:false}, bottomCalc:"sum", minWidth:80},
                    {title:"Lvl 3", field:"lvl3", sorter:"number", align:"center", formatter:"money", formatterParams:{precision:false}, bottomCalc:"sum", minWidth:80},
                    {title:"Score", field:"score", sorter:"number", align:"center", formatterParams:{precision:true}, bottomCalc:"avg"}
                ]
            }
        }
    }
}
</script>

我希望数据输出在表格内看起来像这样。

[
  {
    "name": "Hron",
    "lvl2": 5,
    "lvl3": 0,
    "score": 5
  },
  {
    "name": "Zhr",
    "lvl2": 2,
    "lvl3": 1,
    "score": 3
  },
  {
    "name": "Mang",
    "lvl2": 4,
    "lvl3": 1,
    "score": 5
  }
]

我一直在查看文档,但找不到任何东西。

谢谢

标签: javascriptvue.jstabulator

解决方案


您将需要使用mutator来实现此目的。

如果我们从一些包含两列值的样本数据开始

var data = [
    {col1:27, col2:55}
];

然后定义一个自定义的 mutator 函数来计算这两行的总和

var customMutator = function(value, data, type, params, component){
    //value - original value of the cell
    //data - the data for the row
    //type - the type of mutation occurring  (data|edit)
    //params - the mutatorParams object from the column definition
    //component - when the "type" argument is "edit", this contains the cell component for the edited cell, otherwise it is the column component for the column

    return data.col1 + data.col2 ; //return the sum of the other two columns.
}

然后在我们的列定义中,我们添加第三列,其中包含一个组成的字段名称,并在mutator属性上设置 mutator 函数:

columns:[
    {title:"Column 1", field:"col1"},
    {title:"Column 2", field:"col2"},
    {title:"Sum Column", field:"sumCol", mutator:customMutator}, //make column the sum of the other two columns
]

完整的细节可以在Mutator 文档中找到


推荐阅读