1、新建 number-thousander-format.ts
import { Directive, DirectiveBinding } from "vue";
const numberThousanderFormat: Directive = {
mounted(el, binding: DirectiveBinding) {
const value = binding.value.text || "0";
const parsedValue = parseFloat(value);
if (!isNaN(parsedValue)) {
const formattedValue = parsedValue.toLocaleString("en-US", {
minimumFractionDigits: 0,
maximumFractionDigits: parsedValue % 1 === 0 ? 0 : binding.value.digit,
});
el.innerText = formattedValue;
}
},
};
export default numberThousanderFormat;
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-thousander-format="{ text: num, digit: 4 }"
>
{{ num }}
</div>
其中,自定义指令 numberThousanderFormat 的实现方式为:
- 首先,从指令的参数
binding
中获取要处理的数据value
。 - 然后,将
value
转换为浮点数parsedValue
。 - 如果
parsedValue
是一个合法的数值类型,根据其是否为整数来选择显示方式。- 如果是整数,使用
toLocaleString()
方法来添加千分符,minimumFractionDigits: 0
表示保留 0 位小数,即显示整数。 - 如果不是整数,使用
toLocaleString()
方法来添加千分符,maximumFractionDigits: 2
表示保留 2 位小数,即显示带两位小数的浮点数。
- 如果是整数,使用
- 最后,将处理后的结果显示在元素上。
在上面的代码中,我们在 Vue 的模板中使用 v-number-thousander-format 指令来对数字进行格式化。如果指令的参数是数字类型,指令会根据数据类型,将其显示为整数或带两位小数的浮点数,并添加千分符;如果参数不是数字类型,则不会对该元素进行处理。