gpt4 book ai didi

javascript - Vue 自定义过滤器在全局定义时不起作用

转载 作者:行者123 更新时间:2023-11-28 06:52:07 25 4
gpt4 key购买 nike

这是 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
}
})

关于javascript - Vue 自定义过滤器在全局定义时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32868713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com