vue过滤器的使用

2019-11-23  本文已影响0人  Yin先生

过滤器的介绍:

1、在Vue中使用过滤器(Filters)来渲染数据是一种很有趣的方式。
2、首先我们要知道,Vue中的过滤器不能替代Vue中的methods、computed或者watch,
3、过滤器不改变真正的data,而只是改变渲染的结果,并返回过滤后的版本。
4、在很多不同的情况下,过滤器都是有用的,比如尽可能保持API响应的干净,并在前端处理数据的格式。

可以通过 Scoped slot 可以获取到 row, column, $index 和 store(table 内部的状态管理)的数据。
image.png

html:

<el-table :data="tableData" style="width: 100%">
      <el-table-column prop="price" label="单价">
          <template slot-scope='scope'>
            {{scope.row.price | paiceFilters}}
          </template>
      </el-table-column>
      <el-table-column prop="Tax" label="税率(%)">
        <template slot-scope='scope'>
            {{scope.row.Tax | taxFilters}}
          </template>
      </el-table-column>
      <el-table-column prop="totalPrices"label="总价(元)">
        <template slot-scope='scope'>
            {{scope.row.totalPrices | totalPricesFilters}}
          </template>
      </el-table-column>
<el-table-column prop="statusPrice" label="状态">
        <template slot-scope='scope'>
            {{scope.row.statusPrice | statusFilters}}
          </template>
      </el-table-column>
</el-table>

js:
(注意toFixed方法只能用于数值型数据)

 filters:{
            // 美元过滤器
            paiceFilters:function (value) {
                return '$' + value + '元'
            },
            // 税率过滤器
            taxFilters:function (value) {
                return  parseFloat(value).toFixed(2) + '%'
            },
            // 总价过滤器:保留两位小数四舍五入、加千分位符号
            totalPricesFilters:function (value) {
                return  value.toFixed(2).replace(/\d{1,3}(?=(\d{3})+\b)/g, '$&,')
            },
           // 状态过滤器
            statusFilters:function (value) {
                return  value == 0 ? '正常' : value == 1 ? '冻结' :'未知'
            }
        }
上一篇下一篇

猜你喜欢

热点阅读