Vue 框架中的十进制格式
Decimal Formatting in Vue Framework
我是 Vue 框架的新手。我的要求是在输入框中添加货币格式。
格式:
我需要在焦点外添加一个带两个零的小数,并在焦点内删除零。v-modal 值不应更改,因为此格式仅供用户显示。
我发现这个解决方案非常接近我的要求:https://jsfiddle.net/mani04/w6oo9b6j。还有两件事我无法实现。
我想像这样使用它:
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
- 我添加了 vee-validate.js 库来验证我的整个表单。那么如何在这个例子中使用 v-validate 呢?
- 我不想四舍五入我的字符串。我们只需要添加和删除 (.00)
在这里,如果用户输入 35.7896,它就是 35.79。根据我的要求,它应该保持为 35.7896,因为它已经有小数了。它应该只在用户输入数字时添加小数。
我该怎么做?我应该为此使用 Vue 指令吗?
https://jsfiddle.net/mani04/w6oo9b6j/
我想要这样的东西
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
您不需要 focus-out/focus-in 方法。您需要的是计算的 property。
试试这个:
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 "[=10=].00"}
return "$" + parseFloat(this.currencyValue).toFixed(2)
}
}
});
new Vue({
el: '#app'
});
我认为你可以使用 {{ parseFloat.($variable).toFixed(2) }}
,对于 vue.js 的十进制数来说很简单。你可以试试这个。
methods: {
formatNumber (num) {
return parseFloat(num).toFixed(2)
},
}
在模板中
{{ formatNumber($variable) }}
我是 Vue 框架的新手。我的要求是在输入框中添加货币格式。
格式:
我需要在焦点外添加一个带两个零的小数,并在焦点内删除零。v-modal 值不应更改,因为此格式仅供用户显示。
我发现这个解决方案非常接近我的要求:https://jsfiddle.net/mani04/w6oo9b6j。还有两件事我无法实现。
我想像这样使用它:
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
- 我添加了 vee-validate.js 库来验证我的整个表单。那么如何在这个例子中使用 v-validate 呢?
- 我不想四舍五入我的字符串。我们只需要添加和删除 (.00) 在这里,如果用户输入 35.7896,它就是 35.79。根据我的要求,它应该保持为 35.7896,因为它已经有小数了。它应该只在用户输入数字时添加小数。
我该怎么做?我应该为此使用 Vue 指令吗?
https://jsfiddle.net/mani04/w6oo9b6j/
我想要这样的东西
<my-currency-input id="test1" name="test2" v-model="price" v-validate="required|numeric” ></my-currency-input>
您不需要 focus-out/focus-in 方法。您需要的是计算的 property。 试试这个:
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 "[=10=].00"}
return "$" + parseFloat(this.currencyValue).toFixed(2)
}
}
});
new Vue({
el: '#app'
});
我认为你可以使用 {{ parseFloat.($variable).toFixed(2) }}
,对于 vue.js 的十进制数来说很简单。你可以试试这个。
methods: {
formatNumber (num) {
return parseFloat(num).toFixed(2)
},
}
在模板中
{{ formatNumber($variable) }}