vue js 实现货币
货币格式化方法
使用 Vue.filter 定义全局过滤器,通过 toLocaleString 方法实现货币格式化。
Vue.filter('currency', function (value) {
return value.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
});
在模板中使用过滤器:
<p>{{ price | currency }}</p>
自定义指令实现
创建自定义指令 v-currency 自动格式化输入框中的货币值。
Vue.directive('currency', {
bind(el, binding, vnode) {
el.value = binding.value.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
},
update(el, binding) {
el.value = binding.value.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
}
});
使用指令:
<input v-currency="amount" />
计算属性方案
通过计算属性动态格式化货币显示。
new Vue({
data: {
price: 1234.56
},
computed: {
formattedPrice() {
return this.price.toLocaleString('en-US', {
style: 'currency',
currency: 'USD'
});
}
}
});
模板中使用:
<p>{{ formattedPrice }}</p>
第三方库方案
安装 accounting-js 库进行更复杂的货币处理。
npm install accounting-js
在组件中使用:
import accounting from 'accounting';
export default {
methods: {
formatMoney(value) {
return accounting.formatMoney(value, {
symbol: "$",
precision: 2,
thousand: ",",
decimal: "."
});
}
}
}
多货币切换
实现动态货币切换功能。
data() {
return {
amount: 1000,
currentCurrency: 'USD'
}
},
methods: {
switchCurrency(currency) {
this.currentCurrency = currency;
},
formatCurrency(value) {
return value.toLocaleString(undefined, {
style: 'currency',
currency: this.currentCurrency
});
}
}
模板示例:

<button @click="switchCurrency('USD')">USD</button>
<button @click="switchCurrency('EUR')">EUR</button>
<p>{{ formatCurrency(amount) }}</p>






