我正在尝试编写价格输入的代码。任务应该很简单,但是有些东西不起作用.. 我有一个 Vue 项目,我需要用户在输入字段中输入价格,其中价格应填写最后一个字符。示例:起始值“00.00”;当用户输入“1”时,值变为“00.01”,当用户添加“4”时,值变为“00.14”,当添加2时,值变为“01.42”。
代码是有效的,但只是输入的数字留在输入字段中,即使我添加
event.target.value = ""
;
new Vue({
el: '#app',
data: {
price: '00.00'
},
methods: {
handleKeyDown(event) {
const key = event.key;
const validKeys = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
if (!validKeys.includes(key)) {
event.preventDefault();
return;
}
const newPrice = this.price.replace('.', '') + key;
const parsedPrice = parseFloat(newPrice);
if (isNaN(parsedPrice) || parsedPrice > 9999) {
event.preventDefault();
return;
}
const priceWithDecimal = (parsedPrice / 100).toFixed(2);
this.price = "0" + priceWithDecimal;
// event.target.value = "";
console.log(this.price);
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<input type="text" v-model="price" @keydown="handleKeyDown">
</div>
您可以
watch
price
值进行更改。
const
parseValue = (v) => parseInt(v.trim().replace(/\./g, ''), 10),
formatValue = (v) => (v / 100).toFixed(2).replace(/^(\d)(?=\.)/, '0$1');
new Vue({
el: '#app',
data: {
price: '00.00'
},
watch: {
price(newValue, oldValue) {
const parsed = parseValue(newValue);
this.price = !isNaN(parsed) ? formatValue(parsed) : oldValue;
}
}
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
<input type="number" v-model="price" step="0.01">
</div>
不要重新发明轮子。
new Vue({
el: '#app',
data: {
price: 0
},
watch: {
price(val) {
this.price = Math.round(val * 100) / 100;
}
},
computed: {
priceFormated() {
return this.price.toLocaleString('en-US',
{
style:"currency",
currency:"USD",
minimumIntegerDigits: 2,
useGrouping: false
});
}
}
});
#app { line-height: 2; }
[v-cloak] { display: none; }
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<div id="app">
<input v-model="price" type="number" placeholder="1.0" step="0.01" min="0" max="10" /><br/>
<button @click="price -= 1">-1</button>
Price: {{priceFormated}}
<button @click="price += 1">+1</button>
</div>