Vue 2中使用v-edit-dialog修改值后toCurrency过滤器失效求助
问题原因
通过v-text-field修改价格后,item.price会被赋值为字符串类型,而你的toCurrency过滤器仅对number类型的值执行格式化逻辑,当值为字符串时直接返回原值,因此不再显示货币格式。
修复方案
方案1:给文本框添加.number修饰符
利用Vue的v-model.number修饰符自动将输入文本转为数字类型,确保item.price始终保持数字格式:
<template v-slot:item.price="{item}"> <v-edit-dialog large :return-value.sync="item.price" > {{ item.price | toCurrency}} <template v-slot:input> <v-text-field v-model.number="item.price" label="Edit price" single-line ></v-text-field> </template> </v-edit-dialog> </template>
方案2:修改过滤器兼容字符串类型
调整过滤器逻辑,先将输入值转为数字再判断有效性,即使值为字符串也能正常格式化:
Vue.filter('toCurrency', function (value) { const numValue = Number(value); if (isNaN(numValue)) { return value; } const formatter = new Intl.NumberFormat('eu-EU', { style: 'currency', currency: 'EUR' }); return formatter.format(numValue); });
方案3:手动处理对话框保存事件
移除return-value.sync,改用@save事件手动将返回值转为数字后赋值:
<template v-slot:item.price="{item}"> <v-edit-dialog large :return-value="item.price" @save="item.price = parseFloat($event) || 0" > {{ item.price | toCurrency}} <template v-slot:input> <v-text-field v-model="item.price" label="Edit price" single-line ></v-text-field> </template> </v-edit-dialog> </template>
内容的提问来源于stack exchange,提问作者moody
相关产品推荐
相关产品推荐

