vue3 整数还是显示整数,有小数的保留两位小数显示,写一个指令

发布时间 2023-05-31 14:24:48作者: 小小菜鸟04

1、新建number-format.ts

import { Directive, DirectiveBinding } from "vue";

const numberFormat: Directive = {
  mounted(el, binding: DirectiveBinding) {
    const value = binding.value.text || "0";
    const parsedValue = parseFloat(value);
    if (!isNaN(parsedValue)) {
      // 如果是整数,显示整数,否则显示保留n位小数的浮点数
      if (Number.isInteger(parsedValue)) {
        el.innerText = parsedValue.toFixed(0);
      } else {
        el.innerText = parsedValue.toFixed(binding.value.digit); // 保留n位小数
      }
    }
  },
};

export default numberFormat;
2、新建index.ts
// import directives
import { App } from "vue";
import numberFormat from "./number-format";
import numberThousanderFormat from "./number-thousander-format";

const directivesList: any = {
  // Custom directives
  numberFormat,
  numberThousanderFormat,
};

const directives = {
  install: function (app: App<Element>) {
    Object.keys(directivesList).forEach((key) => {
      // 注册自定义指令
      app.directive(key, directivesList[key]);
    });
  },
};

export default directives;
3、main.ts
import directives from "@/directive/index";
app.use(directives);
4、页面使用
<div
                v-number-format="{
                  text: ell_total_price,
                  digit: 2,
                }"
              >
                {{ sell_total_price }}
              </div>
 

其中,自定义指令 numberFormat 的实现方式为:

  1. 首先,从指令的参数 binding 中获取要处理的数据 value
  2. 然后,将 value 转换为浮点数 parsedValue
  3. 如果 parsedValue 是一个合法的数值类型,根据其是否为整数来选择显示方式。
    • 如果是整数,使用 toFixed(0) 方法来保留 0 位小数,即显示整数。
    • 如果不是整数,使用 toFixed(2) 方法来保留 2 位小数,即显示带两位小数的浮点数。
  4. 最后,将处理后的结果显示在元素上。

在上面的代码中,我们在 Vue 的模板中使用 v-number-format 指令来对数字进行格式化。如果指令的参数是数字类型,指令会根据数据类型,将其显示为整数或带两位小数的浮点数;如果参数不是数字类型,则不会对该元素进行处理。