过滤器filter

定义: 对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)。
语法:

  1. 注册过滤器: Vue.filter(name, callback)或者new Vue(filters:{})
  2. 使用过滤器:{{xxx | 过滤器名}} 或 v-bind:属性="xxx | 过滤器名"

信息

  1. 过滤器也可以接受额外参数、多个过滤器也可以串联
  2. 并没有改变原本的数据,是产生新的对应的数据
html
<div id="editor">

    <h2>显示格式化的日期</h2>

    <!-- 使用filter实现   -->

    <div >{{now | dateTimeFormat}}</div>

    <!-- 使用filter传参实现   -->

    <div >{{now | dateTimeFormat('YYYY/MM/DD')}}</div>

    <!-- 使用methods实现   -->

    <div >{{fmtDate()}}</div>

    <!-- 使用computed实现   -->

    <div >{{getFmtDate}}</div>

</div>
js
Vue.config.productionTip = false

/*全局注册filter*/

Vue.filter('getYear',function (value){

    return value.slice(0,4)

})

new Vue({

    el: "#editor",

    data() {

        return {

            fmtDateStr: '',

            now: 1698418708531

        }

    },

    methods:{

        fmtDate(){

            return dayjs(this.now).format('YYYY年MM月DD日 HH:mm:ss')

        }

    },

    filters:{

        dateTimeFormat(value, formatStr='YYYY-MM-DD HH:mm:ss'){

            return dayjs(this.now).format(formatStr)

        }

    },

    computed:{

        getFmtDate(){

            return dayjs(this.now).format('YYYY年MM月DD日 HH:mm:ss')

        }

    }

})
其中dayjs是实现格式化日期作用的第三方库,相比moment.js更精简但功能完全一致,运行效果: ![Alt text](/web/vue/images/1708605125071.jpg)

评论