vue 过滤器基本使用

Vue.js 允许你自定义过滤器,可被用于一些常见的文本格式化,例如时间戳格式化。

过滤器可以用在:

  • 双花括号插值
  • v-bind 表达式 (2.1.0+ 开始支持)。

过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符号指示:

<!-- 在双花括号中 -->
{{ timestamp | format }}

<!-- 在 `v-bind` 中 -->
<div v-bind:time="timestamp | format"></div>

全局注册

<!--时间戳转换为时间-->
Vue.filter('format', function (value) { 
   const date = new Date(value)
   return `${date.getFullYear()}-${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
})

组件中局部注册

new Vue({
  el: '#app',
  data: {
      timestamp: 1548918359000,
  },
 
  filters: {
    format: function(value) {
        const date = new Date(value)
        return `${date.getFullYear()}-${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate()} ${date.getHours()}:${date.getMinutes()}:${date.getSeconds()}`
    },
  },
)}

链式用法

过滤器可以串联:

{{ message | filterA | filterB }}

在这个例子中,filterA 被定义为接收单个参数的过滤器函数,表达式 message 的值将作为参数传入到函数中。然后继续调用同样被定义为接收单个参数的过滤器函数 filterB,将 filterA 的结果传递到 filterB 中。

需注意过滤器的先后顺序。

接收参数

过滤器是 JavaScript 函数,因此可以接收参数:

{{ message | filterA('arg1', arg2) }}

这里,filterA 被定义为接收三个参数的过滤器函数。其中 message 的值作为第一个参数,普通字符串 'arg1' 作为第二个参数,表达式 arg2 的值作为第三个参数。

posted @ 2019-01-31 15:21  Mr.曹  阅读(5468)  评论(0编辑  收藏  举报