Skip to content

VJSP Vue3 Frame - Utility Functions Guide

Overview

The VJSP Vue3 Frame provides a comprehensive utility function library that supports various aspects of frontend development, including caching management, security protection, routing and permissions, message management, and more. This guide details the architecture, usage methods, and best practices of the utility functions.

Architecture Design

1. Directory Structure

utils/
├── cache/                    # Cache management layer
│   ├── CacheUtil.ts         # Cache utility class
│   ├── MemoryCache.ts       # Memory cache implementation
│   └── StorageCache.ts      # Persistent storage cache
├── security/                # Security protection layer
│   ├── SecurityManager.ts    # Security manager
│   ├── RateLimiter.ts       # Rate limiting
│   └── CSRFProtection.ts    # CSRF protection
├── router/                  # Routing and permissions
│   ├── RouterHelper.ts      # Routing helper
│   ├── PermissionUtil.ts    # Permission utility
│   └── RouteGuard.ts        # Route guard
├── message/                # Message management
│   ├── MessageManager.ts    # Message manager
│   └── NotificationUtil.ts  # Notification utility
├── common/                 # Common utilities
│   ├── DateUtil.ts         # Date utilities
│   ├── StringUtil.ts       # String utilities
│   └── ObjectUtil.ts       # Object utilities
└── index.ts               # Unified export

2. Design Principles

Single Responsibility Principle: Each utility function focuses on a specific functionality

Modular Design: Independent modules with clear interfaces

Type Safety: Full TypeScript support with complete type definitions

Performance Optimization: Efficient implementation with minimal overhead

Security Protection: Built-in security mechanisms

Core Utility Mechanisms

1. Cache Management

Memory Cache Features:

  • In-memory data storage
  • Automatic expiration management
  • Memory leak prevention
  • Performance monitoring

Storage Cache Features:

  • LocalStorage/SessionStorage support
  • Data serialization/deserialization
  • Storage quota management
  • Cross-tab synchronization

2. Security Protection

Rate Limiting Mechanism:

  • Multi-level rate limiting (global/user/endpoint)
  • Sliding window algorithm
  • Dynamic configuration adjustment
  • Real-time monitoring

CSRF Protection:

  • Token generation and validation
  • Double-submit cookie pattern
  • Automatic token refresh
  • Request header protection

3. Routing and Permissions

Route Guard Features:

  • Permission verification
  • Route redirection
  • Login status checking
  • Route caching management

Permission Utility Features:

  • Permission checking
  • Permission filtering
  • Dynamic permission loading
  • Permission level management

4. Message Management

Message Types:

  • Success messages
  • Warning messages
  • Error messages
  • Information messages

Notification Features:

  • Automatic hiding
  • Position configuration
  • Custom duration
  • Stack management

Product Module Development Example

1. Product Data Cache Implementation

typescript
// src/views/product/ProductList.vue
<script setup lang="ts">
import { CacheUtil } from '@/utils/cache'
import { message } from '@/utils/messageManager'

// Cache configuration
const PRODUCT_CACHE_KEY = 'product_list_cache'
const CACHE_EXPIRY = 5 * 60 * 1000 // 5 minutes

// Product list data
const productList = ref([])
const loading = ref(false)

// Load product data with cache
const loadProductList = async () => {
  try {
    loading.value = true

    // Check cache first
    const cachedData = CacheUtil.get(PRODUCT_CACHE_KEY)
    if (cachedData && !CacheUtil.isExpired(PRODUCT_CACHE_KEY)) {
      productList.value = cachedData
      console.log('Loaded from cache')
      return
    }

    // Fetch from API
    const response = await productApi.getList()
    productList.value = response.data

    // Update cache
    CacheUtil.set(PRODUCT_CACHE_KEY, productList.value, CACHE_EXPIRY)
    console.log('Loaded from API and cached')

  } catch (error) {
    message.error('Failed to load product list')
    console.error('Product loading error:', error)
  } finally {
    loading.value = false
  }
}

// Clear product cache
const clearProductCache = () => {
  CacheUtil.remove(PRODUCT_CACHE_KEY)
  message.success('Product cache cleared')
}

// Refresh product data
const refreshProductList = () => {
  CacheUtil.remove(PRODUCT_CACHE_KEY)
  loadProductList()
}

// Initialize on component mount
onMounted(() => {
  loadProductList()
})
</script>

<template>
  <div class="product-list">
    <div class="header">
      <h2>Product Management</h2>
      <div class="actions">
        <el-button @click="refreshProductList" :loading="loading">
          Refresh
        </el-button>
        <el-button @click="clearProductCache" type="warning">
          Clear Cache
        </el-button>
      </div>
    </div>

    <el-table :data="productList" v-loading="loading">
      <!-- Table columns -->
    </el-table>
  </div>
</template>

2. Product Permission Control Implementation

typescript
// src/views/product/components/ProductActions.vue
<script setup lang="ts">
import { hasPermission, filterByPermission } from '@/utils/permission'

// Product operation permissions definition
const PRODUCT_PERMISSIONS = {
  CREATE: 'product:create',
  EDIT: 'product:edit',
  DELETE: 'product:delete',
  VIEW: 'product:view'
}

// Check current user permissions
const canCreateProduct = hasPermission(PRODUCT_PERMISSIONS.CREATE)
const canEditProduct = hasPermission(PRODUCT_PERMISSIONS.EDIT)
const canDeleteProduct = hasPermission(PRODUCT_PERMISSIONS.DELETE)

// Product operation button configuration
const actionButtons = [
  {
    label: 'Create Product',
    icon: 'plus',
    permission: PRODUCT_PERMISSIONS.CREATE,
    handler: () => createProduct()
  },
  {
    label: 'Edit Product',
    icon: 'edit',
    permission: PRODUCT_PERMISSIONS.EDIT,
    handler: () => editProduct()
  },
  {
    label: 'Delete Product',
    icon: 'delete',
    permission: PRODUCT_PERMISSIONS.DELETE,
    handler: () => deleteProduct()
  }
]

// Filter operation buttons by permission
const visibleButtons = filterByPermission(actionButtons, 'permission')

// Product operation functions
const createProduct = () => {
  if (!hasPermission(PRODUCT_PERMISSIONS.CREATE)) {
    message.warning('No permission to create product')
    return
  }
  // Create product logic
}

const editProduct = () => {
  if (!hasPermission(PRODUCT_PERMISSIONS.EDIT)) {
    message.warning('No permission to edit product')
    return
  }
  // Edit product logic
}

const deleteProduct = () => {
  if (!hasPermission(PRODUCT_PERMISSIONS.DELETE)) {
    message.warning('No permission to delete product')
    return
  }
  // Delete product logic
}
</script>

<template>
  <div class="product-actions">
    <el-button
      v-for="button in visibleButtons"
      :key="button.label"
      :icon="button.icon"
      @click="button.handler"
    >
      {{ button.label }}
    </el-button>
  </div>
</template>

3. Product Route Configuration and Caching

typescript
// src/router/modules/product.ts
import { Layout } from '@/utils/routerHelper'
import type { AppRouteRecordRaw } from '@/types/router'

const ProductRoute: AppRouteRecordRaw = {
  path: '/product',
  component: Layout,
  redirect: '/product/list',
  name: 'Product',
  meta: {
    title: 'Product Management',
    icon: 'shopping',
    permission: 'product',
    keepAliveName: 'ProductLayout',
  },
  children: [
    {
      path: 'list',
      component: () => import('@/views/product/ProductList.vue'),
      name: 'ProductList',
      meta: {
        title: 'Product List',
        icon: 'list',
        permission: 'product:view',
        keepAliveName: 'ProductList',
        noCache: false, // Enable caching
      },
    },
    {
      path: 'detail/:id',
      component: () => import('@/views/product/ProductDetail.vue'),
      name: 'ProductDetail',
      meta: {
        title: 'Product Details',
        icon: 'detail',
        permission: 'product:view',
        keepAliveName: 'ProductDetail',
        noCache: true, // Disable caching (detail pages usually don't need caching)
      },
      props: true,
    },
    {
      path: 'create',
      component: () => import('@/views/product/ProductCreate.vue'),
      name: 'ProductCreate',
      meta: {
        title: 'Create Product',
        icon: 'plus',
        permission: 'product:create',
        noCache: true, // Creation pages don't need caching
      },
    },
  ],
}

export default ProductRoute

4. Product API Security Protection

typescript
// src/api/product.ts
import { securityManager } from '@/utils/securityManager'
import { message } from '@/utils/messageManager'

class ProductApi {
  private baseURL = '/api/product'

  // Get product list (with rate limiting)
  async getList(params?: any) {
    // Check rate limiting
    const userId = this.getCurrentUserId()
    const endpoint = `${this.baseURL}/list`

    if (!securityManager.isRequestAllowed(userId, endpoint)) {
      message.warning('Request too frequent, please try again later')
      throw new Error('Rate limit exceeded')
    }

    // Add CSRF protection headers
    const headers = securityManager.getCSRFHeaders('GET')

    return await axios.get(endpoint, {
      params,
      headers,
    })
  }

  // Create product (with security verification)
  async create(productData: any) {
    const userId = this.getCurrentUserId()
    const endpoint = `${this.baseURL}/create`

    // Check rate limiting
    if (!securityManager.isRequestAllowed(userId, endpoint)) {
      message.warning('Operation too frequent, please try again later')
      throw new Error('Rate limit exceeded')
    }

    // Add CSRF protection headers
    const headers = securityManager.getCSRFHeaders('POST')

    return await axios.post(endpoint, productData, { headers })
  }

  // Delete product (with permission verification)
  async delete(productId: string) {
    const userId = this.getCurrentUserId()
    const endpoint = `${this.baseURL}/delete/${productId}`

    // Check rate limiting
    if (!securityManager.isRequestAllowed(userId, endpoint)) {
      message.warning('Operation too frequent, please try again later')
      throw new Error('Rate limit exceeded')
    }

    // Add CSRF protection headers
    const headers = securityManager.getCSRFHeaders('DELETE')

    return await axios.delete(endpoint, { headers })
  }

  private getCurrentUserId(): string {
    // Logic to get current user ID
    const userStore = useUserStore()
    return userStore.getUserInfo?.id || 'anonymous'
  }
}

export const productApi = new ProductApi()

Performance Optimization Practices

1. Cache Strategy Optimization

Product List Cache Optimization:

  • Use memory cache + persistent cache dual mechanism
  • Set appropriate expiration times based on data update frequency
  • Implement cache preloading mechanism to improve user experience

2. Component Cache Configuration

keep-alive Cache Strategy:

vue
<!-- src/layout/components/AppMain.vue -->
<template>
  <section class="app-main">
    <router-view v-slot="{ Component }">
      <transition name="fade-transform" mode="out-in">
        <keep-alive :include="cachedViews">
          <component :is="Component" :key="route.path" />
        </keep-alive>
      </transition>
    </router-view>
  </section>
</template>

<script setup lang="ts">
import { useTagsViewStore } from '@/layout/stores/tagsView'

const route = useRoute()
const tagsViewStore = useTagsViewStore()

// Get cached view list
const cachedViews = computed(() => tagsViewStore.getCachedViews)
</script>

3. Request Optimization Strategy

Product API Request Optimization:

  • Implement request deduplication to avoid duplicate requests
  • Use request caching to reduce server pressure
  • Implement request priority management, important requests processed first

Best Practices Guide

1. Utility Function Usage Standards

Import Standards:

typescript
// Recommended: Import on demand
import { CacheUtil } from '@/utils/cache'
import { hasPermission } from '@/utils/permission'

// Not recommended: Global import (increases bundle size)
import * as utils from '@/utils'

Error Handling Standards:

typescript
// Use try-catch to handle utility function exceptions
try {
  const userInfo = SecurityStorage.getUserInfo()
} catch (error) {
  console.error('Failed to get user info:', error)
  // Fallback handling or user notification
}

2. Cache Usage Recommendations

Suitable for caching:

  • Static configuration data
  • Basic user information
  • Product category data
  • Permission menu data

Not suitable for caching:

  • Data requiring real-time updates
  • Frequently updated business data
  • Sensitive transaction data

3. Security Protection Configuration

Production Environment Configuration:

typescript
// Enable strict security protection
const securityConfig = {
  rateLimit: {
    enabled: true,
    global: { maxRequests: 100, timeWindow: 60000 },
    user: { maxRequests: 10, timeWindow: 60000 },
    endpoint: { maxRequests: 5, timeWindow: 60000 },
  },
  csrf: {
    enabled: true,
    tokenExpiry: 30 * 60 * 1000, // 30 minutes
    doubleSubmit: true,
  },
}

Summary

The VJSP Vue3 Frame utility function library provides powerful foundational support for project development. Through reasonable module division, comprehensive mechanism design, and performance optimization strategies, the utility function library can effectively improve development efficiency and code quality. In actual development, it is recommended to select appropriate utility functions based on specific business requirements and follow best practice standards.