因为VUE3不支持filter语法所以用全局函数替代
- 创建一个filter.ts文件,定义一个千分符过滤方法并导出
//千分符
export function ThousandSeparator(number: any) {
return (
number && number.toString().replace(/(^|\s)\d+/g, (m) => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
)
}
- 在main.ts文件内声明 过滤器类型
type Filter = {
format<T>(str: T): string
}
- 在main.ts文件内引入全局过滤函数
import * as allFilter from './utils/filter.ts'
- 在main.ts文件内声明过滤器
declare module 'vue' {
// 声明要扩充@vue/runtime-core包的声明.
// 这里扩充"ComponentCustomProperties"接口, 因为他是vue3中实例的属性的类型.
export interface ComponentCustomProperties {
$filters: Filter
}
}
- main.ts文件内 将引入的 allFilter 赋值
app.config.globalProperties.$filters = allFilter
- 使用方法以及效果
<span>{{ $filters.ThousandSeparator(9999) }}</span>