فهرست منبع

✨ feat(directives): 添加数字格式化指令

陈雪 1 ماه پیش
والد
کامیت
a1e60f12cd
4فایلهای تغییر یافته به همراه35 افزوده شده و 0 حذف شده
  1. 17 0
      src/directives/format.ts
  2. 8 0
      src/directives/index.ts
  3. 8 0
      src/env.d.ts
  4. 2 0
      src/main.ts

+ 17 - 0
src/directives/format.ts

@@ -0,0 +1,17 @@
+import { Directive, DirectiveBinding } from 'vue'
+
+type FormatType = 'date' | 'number'
+
+export const vFormat: Directive = {
+  mounted(el: HTMLElement, { value }: DirectiveBinding<FormatType>) {
+    const { textContent } = el
+    if (value === 'date') {
+      el.textContent = new Date(textContent).toLocaleDateString()
+    }
+    if (value === 'number') {
+      if (!Number.isNaN(textContent)) {
+        el.textContent = Number(textContent).toFixed(1)
+      }
+    }
+  },
+}

+ 8 - 0
src/directives/index.ts

@@ -0,0 +1,8 @@
+import { App } from 'vue'
+import { vFormat } from './format'
+
+export type FormatType = 'date' | 'number'
+
+export default function Directives(app: App) {
+  app.directive('format', vFormat)
+}

+ 8 - 0
src/env.d.ts

@@ -1,5 +1,7 @@
 /// <reference types="vite/client" />
 /// <reference types="vite-svg-loader" />
+import { ObjectDirective } from 'vue'
+import { FormatType } from './directives'
 
 declare module '*.vue' {
   import { DefineComponent } from 'vue'
@@ -29,3 +31,9 @@ interface ImportMetaEnv {
 interface ImportMeta {
   readonly env: ImportMetaEnv
 }
+
+declare module 'vue' {
+  interface ComponentCustomProperties {
+    vFormat: ObjectDirective<HTMLElement, FormatType>
+  }
+}

+ 2 - 0
src/main.ts

@@ -6,6 +6,7 @@ import App from './App.vue'
 import { prototypeInterceptor, requestInterceptor } from './interceptors'
 import i18n from './locale/index'
 import store from './store'
+import Directives from './directives'
 
 export function createApp() {
   const app = createSSRApp(App)
@@ -14,6 +15,7 @@ export function createApp() {
   app.use(requestInterceptor)
   app.use(prototypeInterceptor)
   app.use(VueQueryPlugin)
+  app.use(Directives)
 
   return {
     app,