【问题标题】:Vue custom filter does not work when defined globallyVue自定义过滤器在全局定义时不起作用
【发布时间】:2015-09-30 14:27:45
【问题描述】:

这里是 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/

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您应该从全局过滤器中删除 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
      }
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-19
      • 1970-01-01
      • 1970-01-01
      • 2018-05-24
      相关资源
      最近更新 更多