这是 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
}
}
}
})
所以区别在于过滤器的定义方式。但根据文档,它必须是双向的。这里出了什么问题?
最佳答案
您应该从全局过滤器中删除 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
}
})
关于javascript - Vue 自定义过滤器在全局定义时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868713/