Vue项目中常常遇到表格内容要根据接口数据格式化展现,好比:接口返回时间戳格式1560565657109,表格要展现为'2019.06.15 10:27:37'。下面介绍3种格式化数据的方案并简述其使用场景,但愿帮助你们在项目中能够准肯定位快速开发。html
当只须要对数值改变的状况时,可经过 element-ui 表格列属性 formatter
直接实现。vue
<!-- html --> <template> <el-table ref="table" :data="data" fit stripe> <el-table-column prop="name" label="姓名" ></el-table-column> <el-table-column prop="height" label="身高(cm)" ></el-table-column> <el-table-column prop="weight" label="体重(kg)" ></el-table-column> <el-table-column label="BMI" :formatter="bmiFormatter" ></el-table-column> </el-table> </template> <!-- js --> <script> export default { data () { return { data: [{ name: '张三', height: '160', weight: '80' }, { name: '李四', height: '176', weight: '65' }] } }, methods: { bmiFormatter (row, column, cellValue, index) { // row: 行数据 // column: 列属性 // cellValue: 单元格数据值 // index: 行索引,注意:2.3.9版本之后才有。 return (row.weight / Math.pow((row.height / 100), 2)).toFixed(1) } } } </script>
当表格内容根据接口数据须要进行颜色等样式上改变时,须要借助 <template slot-scope="scope"></template>
来实现。element-ui
<!-- html --> <template> <el-table ref="table" :data="data" fit stripe> <el-table-column prop="name" label="姓名" ></el-table-column> <el-table-column label="成绩"> <template slot-scope="scope"> <span :style="{ 'color': scope.row.scores >= 60 ? 'green' : 'red' }"> {{ scope.row.scores }} </span> </template> </el-table-column> </el-table> </template> <!-- js --> <script> export default { data () { return { data: [{ name: '王朝', scores: '86' }, { name: '马汉', scores: '59' }] } } } </script>
当表格内容急须要数据上的转换又须要样式改变时,须要 <template slot-scope="scope"></template>
和 Vue 的过滤器 filters
搭配实现。ide
<!-- html --> <template> <el-table ref="table" :data="data" fit stripe> <el-table-column prop="name" label="姓名" ></el-table-column> <el-table-column label="性别"> <template slot-scope="scope"> <span :style="{ 'color': scope.row.gender === 'male' ? 'blue' : 'red' }"> {{ scope.row.gender | genderFormatter }} </span> </template> </el-table-column> </el-table> </template> <!-- js --> <script> export default { data () { return { data: [{ name: '李雷', gender: 'male' }, { name: '韩梅梅', gender: 'female' }] } }, filters: { genderFormatter (gender) { const map = { male: '♂', female: '♀' } return map[gender] } } } </script>
参考:ui