当全局定义时,自定义过滤器不起作用

Vue custom filter does not work when defined globally

本文关键字:自定义 过滤器 不起作用 全局 定义      更新时间:2023-09-26

这是jsFiddle的例子:

html:

<div id="demo">
  does not show $ sign in input as in second input - why? <br>
  <!-- the diff is only that filter is defined diferently -->    
  <input type="text" v-model="a | currencyDisplay">
  <span >model value: {{a }}</span>
</div>

Js:

Vue.filter('currencyDisplay', {
  currencyDisplay: {
    // model -> view
    // formats the value when updating the input element.
    read: function(val) {
      console.log('filter red');
      return '$'+val.toFixed(2)
    },
    // view -> model
    // formats the value when updating the data.
    write: function(val, oldVal) {
      console.log('filter write');
      var number = +val.replace(/[^'d.]/g, '')
      return isNaN(number) ? 0 : number
    }
  }
})
var demo = new Vue({
  el: '#demo',
  data: {
    a: 5
  }
})

当我查看文档示例的源代码时,他们写了这样的代码:

new Vue({
  el: '#two-way-filter-demo',
  data: {
    money: 123.45
  },
  filters: {
    currencyDisplay: {
      read: function(val) {
        return '$'+val.toFixed(2)
      },
      write: function(val, oldVal) {
        var number = +val.replace(/[^'d.]/g, '')
        return isNaN(number) ? 0 : number
      }
    }
  }
})

区别在于定义过滤器的方式。但根据文件,它必须是双向的。这里出了什么问题?

http://jsfiddle.net/yMv7y/975/

您应该从全局过滤器中删除currencyDisplay键:

Vue.filter('currencyDisplay', {
  read: function (val) {
    return '$' + val.toFixed(2)
  },
  write: function (val, oldVal) {
    var number = +val.replace(/[^'d.]/g, '')
    return isNaN(number) ? 0 : number
  }
})