Vue3常用工具方法封装 (hooks/useUtils.js)

手机号、邮箱、空字符串、身份证、车牌号、解析url地址上&数据、ip、设置&读取&移除cookie、设置&读取&移除localStorage、base64加密&解密等等常用工具方法

import { ref } from 'vue';

export function useUtils() {
  // 正则验证规则
  const regexRules = {
    // 手机号验证
    phone: /^1[3-9]\d{9}$/,
    // 邮箱验证
    email: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
    // 空字符串验证
    empty: /^\s*$/,
    // 身份证验证
    idCard: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
    // 车牌号验证
    carLicense: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/,
    // IP地址验证
    ip: /^((25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(25[0-5]|2[0-4]\d|[01]?\d\d?)$/
  };

  // 验证方法
  const validate = {
    phone: (value) => regexRules.phone.test(value),
    email: (value) => regexRules.email.test(value),
    isEmpty: (value) => regexRules.empty.test(value),
    idCard: (value) => regexRules.idCard.test(value),
    carLicense: (value) => regexRules.carLicense.test(value),
    ip: (value) => regexRules.ip.test(value)
  };

  // 解析URL参数
  const parseUrlParams = (url) => {
    const params = {};
    const urlStr = url || window.location.href;
    const index = urlStr.indexOf('?');
    
    if (index !== -1) {
      const queryString = urlStr.slice(index + 1);
      const queryArray = queryString.split('&');
      
      queryArray.forEach(item => {
        const [key, value] = item.split('=');
        if (key) params[key] = decodeURIComponent(value || '');
      });
    }
    
    return params;
  };

  // Cookie操作
  const cookie = {
    set: (name, value, days = 7) => {
      const date = new Date();
      date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
      const expires = `expires=${date.toUTCString()}`;
      document.cookie = `${name}=${encodeURIComponent(value)}; ${expires}; path=/`;
    },
    get: (name) => {
      const nameEQ = `${name}=`;
      const ca = document.cookie.split(';');
      
      for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) === ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
      }
      
      return null;
    },
    remove: (name) => {
      cookie.set(name, '', -1);
    }
  };

  // localStorage操作
  const storage = {
    set: (name, value) => {
      if (typeof value === 'object') {
        value = JSON.stringify(value);
      }
      localStorage.setItem(name, value);
    },
    get: (name) => {
      const value = localStorage.getItem(name);
      if (!value) return null;
      
      try {
        return JSON.parse(value);
      } catch (e) {
        return value;
      }
    },
    remove: (name) => {
      localStorage.removeItem(name);
    },
    clear: () => {
      localStorage.clear();
    }
  };

  // Base64加密解密
  const base64 = {
    encode: (str) => {
      return window.btoa(unescape(encodeURIComponent(str)));
    },
    decode: (str) => {
      return decodeURIComponent(escape(window.atob(str)));
    }
  };

  // 防抖函数
  const debounce = (func, wait = 300) => {
    let timeout = null;
    return function(...args) {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        func.apply(this, args);
      }, wait);
    };
  };

  // 节流函数
  const throttle = (func, delay = 300) => {
    let lastTime = 0;
    return function(...args) {
      const now = Date.now();
      if (now - lastTime >= delay) {
        func.apply(this, args);
        lastTime = now;
      }
    };
  };

  // 格式化日期
  const formatDate = (date, format = 'yyyy-MM-dd HH:mm:ss') => {
    if (!date) return '';
    if (typeof date === 'number') date = new Date(date);
    if (!(date instanceof Date)) return '';

    const o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'H+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds(),
      'q+': Math.floor((date.getMonth() + 3) / 3),
      'S': date.getMilliseconds()
    };

    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
    }

    for (const k in o) {
      if (new RegExp('(' + k + ')').test(format)) {
        format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
      }
    }

    return format;
  };

  return {
    regexRules,
    validate,
    parseUrlParams,
    cookie,
    storage,
    base64,
    debounce,
    throttle,
    formatDate
  };
}

 

posted @ 2025-08-07 17:05  蜗牛snail  阅读(6)  评论(0)    收藏  举报
蜗牛前端 蜗牛文学