在开发前端应用时,我们经常需要对数据进行一定的格式化处理后再展示给用户。例如时间戳转为可读日期、金额保留两位小数、文本首字母大写等。Vue 提供了一种简洁而强大的机制来实现这一需求 —— 过滤器(Filter) 。
本文将带你深入理解 Vue 中的过滤器用法,包括局部过滤器与全局过滤器的定义方式、如何在模板中调用,以及一些实际应用场景和注意事项。
一、什么是过滤器?
过滤器(Filter) 是 Vue 中用于转换数据输出格式的一种工具。它通常用于文本格式化,并且只能在双花括号插值 {{ }}
或 v-bind
表达式中使用。
特点:
- 可以接收参数
- 支持链式调用
- 不会修改原始数据,只影响显示结果
- 在 Vue 2.x 中广泛使用,在 Vue 3.x 中已不再内置支持(但可通过自定义函数或方法实现类似功能)
二、Vue 2.x 中过滤器的使用方式
⚠️ 注意:Vue 3 已移除过滤器语法,推荐使用方法或 computed 属性替代。本文以 Vue 2.x 为主讲解。
1. 定义局部过滤器(组件内)
局部过滤器是在单个组件内部定义并使用的,适用于特定组件的数据格式化。
<template>
<div>
原始价格:{{ price }}
格式化后价格:{{ price | currency }}
</div>
</template>
<script>
export default {
data() {
return {
price: 99.99
}
},
filters: {
currency(value) {
return '¥' + value.toFixed(2);
}
}
}
</script>
2. 定义全局过滤器(所有组件可用)
全局过滤器可以在整个项目中的任意组件中使用,适合通用格式化逻辑。
// main.js
import Vue from 'vue'
import App from './App.vue'
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
new Vue({
render: h => h(App)
}).$mount('#app')
然后在任意组件中使用:
<p>{{ 'hello world' | capitalize }}</p>
<!-- 输出:Hello world -->
三、过滤器传参
过滤器可以接收额外参数,第一个参数始终是管道符左边的表达式值。
filters: {
formatTime(timestamp, format = 'YYYY-MM-DD') {
const date = new Date(timestamp)
// 简化示例,实际建议使用 moment.js 或 day.js
return `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`
}
}
模板中使用:
<p>{{ 1717027200000 | formatTime }}</p>
<!-- 输出:2024-6-1 -->
四、链式调用过滤器
多个过滤器可以通过管道符串联使用,前一个过滤器的输出作为下一个过滤器的输入。
<p>{{ 'vue filter example' | capitalize | uppercase }}</p>
对应过滤器:
filters: {
capitalize(value) {
return value.replace(/\b\w/g, c => c.toUpperCase())
},
uppercase(value) {
return value.toUpperCase()
}
}
输出结果:VUE FILTER EXAMPLE
五、Vue 3 中如何替代过滤器
在 Vue 3 中,官方已经移除了过滤器语法,推荐使用以下方式替代:
✅ 方法调用(methods)
<template>
<p>{{ formatPrice(price) }}</p>
</template>
<script>
export default {
data() {
return {
price: 89.99
}
},
methods: {
formatPrice(price) {
return '¥' + price.toFixed(2)
}
}
}
</script>
✅ 计算属性(computed)
适用于不需要传参的场景:
computed: {
formattedPrice() {
return '¥' + this.price.toFixed(2)
}
}
<p>{{ formattedPrice }}</p>
✅ 自定义组合函数(Composition API)
适用于 Vue 3 + Composition API:
// useFormat.js
export function useFormat() {
function currency(value) {
return '¥' + value.toFixed(2)
}
return { currency }
}
组件中使用:
<script setup>
import { useFormat } from '@/utils/useFormat'
const { currency } = useFormat()
const price = 123.45
</script>
<template>
<p>{{ currency(price) }}</p>
</template>
六、最佳实践与注意事项
场景 | 推荐做法 |
---|---|
时间格式化 | 使用 day.js / moment.js 封装方法 |
数字格式化 | 使用 Intl.NumberFormat 或 numeral.js |
多语言支持 | 配合 i18n 插件 |
不要修改原始数据 | 过滤器应保持无副作用 |
Vue 3 中避免使用过滤器 | 推荐使用 methods、computed 或组合函数 |
七、结语
感谢您的阅读!如果你有任何疑问或想要分享的经验,请在评论区留言交流!