在vue中,当使用双大括号{ {}}或者v-bind绑定输出指定的值(固定的格式)时,可以通过指定过滤器,来将其转化为所需要格式的值。例如:日期。
1.在组件中使用filters:
<!-- vue中的过滤器 -->
<div>过滤前:{
{ date }}</div>
<div>过滤后:{
{ date | formatDate }}</div>
data() {
return {
date: new Date()
};
},
filters: {
formatDate(val) {
let newDate = ''
let year = val.getFullYear()
let month = val.getMonth() + 1
let day = val.getDate()
newDate = year + '-' + month + '-' + day
return newDate
}
}
2.在js中使用filters:
Vue.filter('formatDate', function (val) {})
3.filters可以串联:
filterA 被定义为接收单个参数的过滤器函数,表达式 message 的值将作为参数传入到函数中。然后继续调用同样被定义为接收单个参数的过滤器函数 filterB,将 filterA 的结果传递到 filterB 中
{
{ message | filterA | filterB }}
4.filters可以接收多个参数:
filterA 被定义为接收三个参数的过滤器函数。其中 message 的值作为第一个参数,普通字符串 'arg1' 作为第二个参数,表达式 arg2 的值作为第三个参数。
{
{ message | filterA('arg1', arg2) }}
以上就是vue中过滤器的基本使用。通过过滤器,能提高代码的服用。