我是 Vue 框架的新手。我的要求是在输入框中添加货币格式。
格式:
我需要在焦点移出时添加带有两个零的小数,并在焦点移入时删除零。v-模态值不应更改,因为此格式仅用于用户显示。
我发现这个解决方案非常接近我的要求:https://jsfiddle.net/mani04/w6oo9b6j。只有两件事我无法实现。
我想这样使用它:
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
我该怎么做?我应该为此使用 Vue 指令吗?
https://jsfiddle.net/mani04/w6oo9b6j/
我想要这样的东西
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
我想你可以使用
{{ parseFloat($variable).toFixed(2) }}
这是 vue.js 中使用的十进制数字的简单技巧
methods: {
formatNumber (num) {
return parseFloat(num).toFixed(2)
},
}
在模板中
{{ formatNumber($variable) }}
您不需要聚焦/聚焦方法。您需要的是一个计算的属性。 试试这个:
Vue.component('my-currency-input', {
template: `
<div>
<input type="text" v-model="currencyValue" /> {{ formattedCurrencyValue }}
</div>`,
data: function() {
return {
currencyValue: 0,
/* formattedCurrencyValue: "$ 0.00" */
}
},
computed: {
formattedCurrencyValue: function(){
if(!this.currencyValue){ return "$0.00"}
return "$" + parseFloat(this.currencyValue).toFixed(2)
}
}
});
new Vue({
el: '#app'
});