vue 过滤器filter
程序员文章站
2024-02-09 16:11:46
...
过滤器常用于过滤 currency / number / date
- 使用:
{{数据名 | 过滤器名(参数1,参数2)}}
v-xxx=”数据名 | 过滤器名(参数1,参数2)” - 定义:
a) Vue.filter(‘过滤器名称’,函数(要过滤的数据,参数))
b) 选项
filters:{
过滤器名称:函数
过滤器名称2:函数(要过滤的数据,参数)
} - 注:需要有返回值
<template>
<div class="test">
<div>初始化日期:
<p>{{today}}</p>
</div>
<div>计算属性格式化日期:
<p>{{finalDateFormate}}</p>
</div>
<div>过滤器格式化日期:
<p>{{today | DateFormatter}}</p>
</div>
</div>
</template>
<script>
export default {
name: 'test',
data () {
return {
today:new Date(),
}
},
filters:{
DateFormatter(date){
const year = date.getFullYear()
const month = date.getMonth() + 1
const day = date.getDate()
const hour = date.getHours()
const minute = date.getMinutes()
const second = date.getSeconds();
const before=[year, month, day].map((n)=>{
n = n.toString();
return n[1] ? n : '0' + n;
}).join('/');
const after=[hour, minute, second].map((n)=>{
n = n.toString();
return n[1] ? n : '0' + n;
}).join(':');
return before+' '+after;
}
},
computed:{
finalDateFormate(){
const year = this.today.getFullYear()
const month = this.today.getMonth() + 1
const day = this.today.getDate()
const hour = this.today.getHours()
const minute = this.today.getMinutes()
const second = this.today.getSeconds();
return [year, month, day].map(this.formatNumber).join('/') + ' ' + [hour, minute, second].map(this.formatNumber).join(':');
}
},
methods: {
formatNumber(n){
n = n.toString();
return n[1] ? n : '0' + n;
}
}
}
</script>