基于封装全局的el-table组件中添加过滤器

先看效果图:

没加过滤器时:

 使用了过滤器之后:

先在调用table组件的页面中,导入过滤器,并在绑定的数据中定义filter

<table v-bind="{...tableConfig}">
</table>
 tableConfig: {
        loading: false,
        data: [],
        column: [
          TableHead('编号', 'code'),
          { ...TableHead('名称', 'name'),showOverflowTooltip: true },
          { ...TableHead('单位名称', 'unitName'), showOverflowTooltip: true },
          { ...TableHead('数量', 'counts') },
          { ...TableHead('单价(元)', 'amount'),filter:numFormats },
          { ...TableHead('合价(元)', 'totalAmount'),filter:numFormats },
        ]
      },

之后在el-table封装的组件中,将 item.filter 判断不为undefined,给展示的数据使用过滤器

<template slot-scope="scope">
     <slot v-if="item.slot" :name="item.slot" :data="{ ...scope }" />
        <span v-else-if="item.stress" class="stress" 
            @click="$emit('view-detail', scope.row)" >
              {
   
   { scope.row[item.prop] ? scope.row[item.prop] : item.placeholder
                  ? item.placeholder : "--" }}</span>
            <!-- 将表格中的单价和合价格式化 -->
            <span v-else-if="item.filter != undefined">
                {
   
   {scope.row[item.prop] | numFormats}}
            </span>
</template>

 过滤器:格式化金额 

// 格式化金额
export function numFormats (value, currency = '元', decimals = 2) {
  value = parseFloat(value);
  if (!value && value !== 0) return '';
  const stringified = Math.abs(value).toFixed(decimals);
  const $int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
  const i = $int.length % 3;
  const head = i > 0 ? ($int.slice(0, i) + ($int.length > 3 ? ',' : '')) : '';
  const $float = decimals ? stringified.slice(-1 - decimals) : '';
  const sign = value < 0 ? '-' : '';
  return `${sign}${head}${$int.slice(i).replace(/(\d{3})(?=\d)/g, '$1,')}${$float} ${currency}`;
};

猜你喜欢

转载自blog.csdn.net/weixin_45990765/article/details/123573658
今日推荐