瀏覽代碼

✨ feat(format): 实现数字格式化指令

陈雪 1 月之前
父節點
當前提交
d0d83461c6
共有 2 個文件被更改,包括 29 次插入11 次删除
  1. 11 4
      src/components/product-list/product-item.vue
  2. 18 7
      src/directives/format.ts

+ 11 - 4
src/components/product-list/product-item.vue

@@ -4,14 +4,17 @@
     <image :src="product.cover" class="w-328rpx" mode="widthFix"></image>
     <view class="product-name">{{ product.name }}</view>
     <view class="sell-rate">
-      <view v-format="'number'" class="rate">
-        {{ product.rate }}
+      <view class="rate">
+        <view v-format.rate>{{ product.rate }}</view>
         <image src="@/static/images/rate.svg" class="w-28rpx ml-8rpx" mode="widthFix"></image>
       </view>
       <view class="sold">{{ product.sold }} Sold</view>
     </view>
     <view class="price-cart">
-      <view class="price">USD {{ product.price }}</view>
+      <view class="flex">
+        USD
+        <view class="ml-8rpx" v-format.price>{{ product.price }}</view>
+      </view>
       <view class="cart">
         <image src="@/static/images/cart.svg" class="w-32rpx" mode="widthFix"></image>
       </view>
@@ -20,7 +23,7 @@
 </template>
 
 <script lang="ts" setup>
-  import { ProductSimpleType } from '@/types/product-type'
+  import { ProductSimpleType } from '@/model/product-type'
 
   defineOptions({
     name: 'ProductItem',
@@ -96,6 +99,10 @@
       line-height: 48rpx; /* 157.143% */
       color: $shop-primary;
 
+      .price {
+        display: flex;
+      }
+
       .cart {
         display: flex;
         align-items: center;

+ 18 - 7
src/directives/format.ts

@@ -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)
       }
     }
   },