Vue2 和 Vue3 过滤器的使用

过滤器在日常开发中也算是比较常见,包括格式化日期、添加货币符号等;在 Vue2 中使用过滤器也比较简单,容易上手,稍微来总结一下 Vue2 中过滤器的使用;

  • 全局过滤器;
// main.js
Vue.filter('dateFormat', function (value) {
    
    
    // ...
    return newValue
})
  • 组件过滤器;
// xxx.vue
export default {
    
    
    filters: {
    
    
        dateFormat: function (value) {
    
    
            // ...
            return newValue
        }
    }
}

在组件中使用

<template>
	<div>
        <span>{
   
   { date | dateFormat }}</span>
    </div>
</template>

在 Vue2 中过滤器可以串联使用,每个过滤器接收的值都是前面返回的值,例如:

{
   
   { date | dateFormat | dateFormat1 }}

当然,过滤器也可以进行传参,我们稍微改造一下:

// main.js
Vue.filter('dateFormat', function (value, format = 'yyyy-MM-dd hh:mm:ss') {
    
    
    switch (format) {
    
    
		// ...
    }
    return newValue
})
<!-- 
	这里的过滤器需要传入两个参数,第一个参数默认是需要过滤的值,这里也就是 date,第二个参数是我们自己传进去的值,这里是'yyyy-MM-dd hh:mm:ss'
-->
<span>{
   
   { date | dateFormat('yyyy-MM-dd hh:mm:ss') }}</span>

总结完 Vue2 的过滤器,我们再来看看 Vue3 中的过滤器,从官网文档来看,Vue3 中是移除了过滤器,官方比较推荐我们使用 computed 或者 method 来替换过滤器;

在这里插入图片描述

当然,也不是说我们完全不能使用过滤器,我们可以在全局实例对象上进行挂载,然后通过 $filters 直接调用或者获取过滤器再进行调用;

// main.js
app.config.globalProperties.$filters = {
    
    
    dateFormat: function (value) {
    
    
        // ...
        return newValue
    }
}
<template>
	<!-- 方式一 -->
	<span>{
   
   { $filters.dateFormat(date) }}</span>
	<!-- 方式二 -->
	<span>{
   
   { dateFormat(date) }}</span>
</template>
<script setup>
import { getCurrentInstance } from 'vue'
const { dateFormat } = getCurrentInstance().appContext.config.globalProperties.$filters
</script>

猜你喜欢

转载自blog.csdn.net/Ljwen_/article/details/127387736
今日推荐