element table 过滤器_Vue的过滤器filters在Element表格el-table中的应用 (Vue「过滤器」的使用,自定义过滤器 filters )...
时间: 2023-12-14 08:37:03 浏览: 60
在Element表格(el-table)中使用Vue的过滤器filters,可以对表格中的数据进行格式化或者筛选。
首先,在Vue实例中定义自己的过滤器。例如:
```
filters: {
// 将数字保留两位小数
toFixed2(value) {
return Number(value).toFixed(2);
},
// 将日期进行格式化
formatDate(value) {
const date = new Date(value);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month}-${day}`;
}
}
```
然后,在Element表格(el-table)的列定义中使用filters属性来指定使用哪个过滤器。例如:
```
<el-table-column prop="price" label="价格" :filters="[{ text: '保留两位小数', value: 'toFixed2' }]"
:filter-method="filterMethod" :filtered-value="filteredPrice"></el-table-column>
<el-table-column prop="date" label="日期" :filters="[{ text: '格式化日期', value: 'formatDate' }]"
:filter-method="filterMethod" :filtered-value="filteredDate"></el-table-column>
```
其中,filters属性的值是一个数组,数组中每个元素都是一个对象,text属性表示过滤器的名称,value属性表示过滤器的名称,即定义的自定义过滤器的名称。
最后,在Vue实例中定义filterMethod方法来实现过滤器的实际功能。例如:
```
methods: {
filterMethod(value, filters) {
const filter = filters[0];
const key = filter.value;
if (key === 'toFixed2') {
return value.toFixed(2);
} else if (key === 'formatDate') {
const date = new Date(value);
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
return `${year}-${month}-${day}`;
}
}
}
```
其中,value表示当前列的值,filters表示当前过滤器的配置列表,filterMethod方法根据value和filters来实现实际的过滤器功能。
最后,使用filtered-value属性来指定当前列的过滤器值,用于筛选表格数据。例如:
```
data() {
return {
filteredPrice: ['toFixed2'],
filteredDate: ['formatDate']
}
}
```
以上就是在Element表格(el-table)中使用Vue的过滤器filters的具体步骤。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)