当前位置:首页 > VUE

vue js 实现货币

2026-02-22 03:38:35VUE

货币格式化方法

使用 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
    });
  }
}

模板示例:

vue js 实现货币

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

标签: 货币vue
分享给朋友:

相关文章

vue实现按卡片轮播

vue实现按卡片轮播

实现卡片轮播的基本思路 在Vue中实现卡片轮播可以通过结合v-for指令和动态样式绑定完成。核心是维护一个当前显示卡片的索引,通过CSS过渡效果实现平滑切换。 基础实现步骤 模板部分 使用v-for…

实现vue组件

实现vue组件

Vue 组件的基本实现 Vue 组件是 Vue.js 的核心特性之一,允许将 UI 拆分为独立、可复用的模块。以下是实现 Vue 组件的几种方式: 单文件组件 (SFC) 使用 .vue 文件格式,…

vue实现alert

vue实现alert

实现自定义 Alert 组件 在 Vue 中可以通过组件化方式实现自定义 Alert 弹窗。以下是基于 Vue 3 的实现示例: 组件代码 (Alert.vue) <template>…

vue实现方法

vue实现方法

Vue 实现方法 Vue 是一种流行的前端框架,用于构建用户界面和单页应用。以下是几种常见的 Vue 实现方法: 创建 Vue 实例 通过 new Vue() 创建一个 Vue 实例,传入配置对象,…

vue实现muli

vue实现muli

Vue 实现多语言(i18n)支持 在 Vue 项目中实现多语言(i18n)功能,通常使用 vue-i18n 插件。以下是具体实现步骤: 安装 vue-i18n npm install vue-i…

vue 实现闪烁

vue 实现闪烁

Vue 实现闪烁效果的方法 方法一:使用 CSS 动画 在 Vue 组件中定义一个闪烁的 CSS 动画,通过绑定 class 或 style 来控制元素的闪烁效果。 <template>…