vue3.0实现过滤器
Vue 3.0 实现过滤器的方法
Vue 3.0 移除了过滤器的概念,但可以通过以下方式实现类似功能:
使用全局方法
通过 app.config.globalProperties 注册全局方法:
const app = createApp(App)
app.config.globalProperties.$filters = {
capitalize(value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
在模板中使用:
<p>{{ $filters.capitalize(message) }}</p>
使用计算属性
在组件内部使用计算属性实现过滤效果:

export default {
data() {
return {
message: 'hello world'
}
},
computed: {
capitalizedMessage() {
return this.message.charAt(0).toUpperCase() + this.message.slice(1)
}
}
}
模板中使用:
<p>{{ capitalizedMessage }}</p>
使用组合式API
在setup中使用函数实现:

import { ref, computed } from 'vue'
export default {
setup() {
const message = ref('hello world')
const capitalizedMessage = computed(() => {
return message.value.charAt(0).toUpperCase() + message.value.slice(1)
})
return {
message,
capitalizedMessage
}
}
}
使用自定义指令
实现一个格式化指令:
const app = createApp(App)
app.directive('format', {
mounted(el, binding) {
el.textContent = binding.value.toUpperCase()
},
updated(el, binding) {
el.textContent = binding.value.toUpperCase()
}
})
模板中使用:
<p v-format="message"></p>
使用第三方库
可以考虑使用像 vue-filter 这样的第三方库来提供过滤器功能。
这些方法都能实现Vue 2.x中过滤器的类似功能,其中计算属性和组合式API是Vue 3推荐的方式,因为它们更符合响应式系统的设计理念。
