toLocaleString作用:在没有指定区域的基本使用时,返回使用默认的语言环境和默认选项格式化的字符串。可点击进入MDN查看
// 千分位分隔符指令
import { Directive, DirectiveBinding } from 'vue'
const thousandSeparator: Directive = {
mounted(el: any, binding: DirectiveBinding) {
// 获取文本
const value = el.innerText
if (value && !isNaN(Number(value))) { // 判断文本是不是数字
// 对其进行转化
el.innerText = Number(value).toLocaleString('en-US')
}
},
updated(el: any, binding: DirectiveBinding) {
const value = el.innerText
if (value && !isNaN(Number(value))) {
el.innerText = Number(value).toLocaleString('en-US')
}
}
}
export default {
thousandSeparator
}
//在mian.ts中注册指令
import { createApp, Directive } from 'vue'
import pinia from './store/index'
import i18n from './i18n'
import router from './router/index'
import App from './App.vue'
// 引入指令文件
import directives from '@/utils/directives'
const app = createApp(App)
app.use(pinia).use(i18n()).use(router).mount('#app')
// 注册指令
Object.keys(directives).forEach(key => {
//Object.keys() 返回一个数组,值是所有可遍历属性的key名
app.directive(key, (directives as { [key: string]: Directive })[key]) //key是自定义指令名字;后面应该是自定义指令的值
})
效果