|
@@ -1,16 +1,27 @@
|
|
|
-import { Directive, DirectiveBinding } from 'vue'
|
|
|
+import { Directive } from 'vue'
|
|
|
|
|
|
-export type FormatType = 'date' | 'number'
|
|
|
+type FormatType = number | string
|
|
|
|
|
|
-export const vFormat: Directive = {
|
|
|
- mounted(el: HTMLElement, { value }: DirectiveBinding<FormatType>) {
|
|
|
+export type FormatDirective = Directive<HTMLElement, FormatType>
|
|
|
+
|
|
|
+/**
|
|
|
+ * Format directive 格式化指令
|
|
|
+ * modifiers参数:
|
|
|
+ * - date: 日期格式化
|
|
|
+ * - price: 格式化价格
|
|
|
+ * - rate: 评分格式化
|
|
|
+ * value: number 格式化小数点 string: 格式化日期
|
|
|
+ */
|
|
|
+export const vFormat: Directive<HTMLElement, FormatType> = {
|
|
|
+ mounted(el, { value, modifiers }) {
|
|
|
const { textContent } = el
|
|
|
- if (value === 'date') {
|
|
|
+ if (modifiers.date) {
|
|
|
el.textContent = new Date(textContent).toLocaleDateString()
|
|
|
}
|
|
|
- if (value === 'number') {
|
|
|
+ if (modifiers.price || modifiers.rate) {
|
|
|
if (!Number.isNaN(textContent)) {
|
|
|
- el.textContent = Number(textContent).toFixed(1)
|
|
|
+ const decimal = typeof value === 'number' ? value : modifiers.price ? 2 : 1
|
|
|
+ el.textContent = Number(textContent).toFixed(decimal)
|
|
|
}
|
|
|
}
|
|
|
},
|