Vue项目公共方法封装
·
封装公共方法能提升代码复用性、降低维护成本,确保功能逻辑一致性。以下为 Vue 项目中常见的公共方法封装场景及实现方式。
日期格式化
处理日期显示格式,支持自定义格式如 YYYY-MM-DD 或 YYYY/MM/DD HH:mm:ss。
// utils/date.js
export function formatDate(date, fmt = 'YYYY-MM-DD') {
if (!date) return '';
const d = new Date(date);
const o = {
'Y+': d.getFullYear(),
'M+': d.getMonth() + 1,
'D+': d.getDate(),
'H+': d.getHours(),
'm+': d.getMinutes(),
's+': d.getSeconds()
};
for (const k in o) {
fmt = fmt.replace(new RegExp(k), match => (o[k] < 10 ? `0${o[k]}` : o[k]).slice(-match.length));
}
return fmt;
}
// 使用示例
// formatDate(new Date(), 'YYYY/MM/DD HH:mm:ss')
防抖与节流
控制高频触发事件的执行频率,如搜索框输入、窗口滚动。
// utils/optimize.js
export function debounce(fn, delay = 300) {
let timer = null;
return function (...args) {
if (timer) clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
export function throttle(fn, interval = 300) {
let lastTime = 0;
return function (...args) {
const now = Date.now();
if (now - lastTime >= interval) {
fn.apply(this, args);
lastTime = now;
}
};
}
// 使用示例
// window.addEventListener('resize', throttle(handleResize, 500));
本地存储操作
统一管理 localStorage 或 sessionStorage,避免重复代码。
// utils/storage.js
export const storage = {
set(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get(key) {
const data = localStorage.getItem(key);
return data ? JSON.parse(data) : null;
},
remove(key) {
localStorage.removeItem(key);
},
clear() {
localStorage.clear();
}
};
// 使用示例
// storage.set('token', 'abc123');
// storage.get('token');
金额格式化
处理金额显示,如添加千分位分隔符或固定小数位。
// utils/currency.js
export function formatMoney(num, decimals = 2) {
if (isNaN(num)) return '0.00';
const n = Number(num).toFixed(decimals);
const parts = n.split('.');
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ',');
return parts.join('.');
}
// 使用示例
// formatMoney(1234567.89) => "1,234,567.89"
深拷贝
解决对象引用导致的修改污染问题。
// utils/clone.js
export function deepClone(obj) {
if (obj === null || typeof obj !== 'object') return obj;
const result = Array.isArray(obj) ? [] : {};
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
// 使用示例
// const newObj = deepClone(originalObj);
环境判断
区分开发、测试、生产环境,动态配置接口地址等。
// utils/env.js
export const isDev = process.env.NODE_ENV === 'development';
export const isProd = process.env.NODE_ENV === 'production';
// 使用示例
// const baseURL = isDev ? 'http://dev.api.com' : 'http://prod.api.com';
全局注册
通过 Vue 插件形式注册公共方法,便于在组件内直接调用。
// plugins/utils.js
import * as utils from '@/utils';
export default {
install(Vue) {
Vue.prototype.$utils = utils;
}
};
// 在 main.js 中注册
// import UtilsPlugin from '@/plugins/utils';
// Vue.use(UtilsPlugin);
// 组件内使用
// this.$utils.formatDate(new Date());
数据类型判断 精确判断常见数据类型。
function getType(value) {
return Object.prototype.toString.call(value).slice(8, -1).toLowerCase();
}
浏览器相关封装
本地存储操作 统一管理localStorage和sessionStorage。
const storage = {
set(key, value) {
localStorage.setItem(key, JSON.stringify(value));
},
get(key) {
const value = localStorage.getItem(key);
return value ? JSON.parse(value) : null;
},
remove(key) {
localStorage.removeItem(key);
}
};
URL参数解析 处理URL查询参数获取与转换。
function getUrlParams(url = window.location.href) {
const params = {};
const query = url.split('?')[1];
if (!query) return params;
query.split('&').forEach(item => {
const [key, value] = item.split('=');
params[decodeURIComponent(key)] = decodeURIComponent(value);
});
return params;
}
业务相关封装
金额格式化 处理金额显示格式,如千分位分隔。
function formatMoney(num, decimals = 2) {
const n = Number(num);
if (isNaN(n)) return '0.00';
return n.toFixed(decimals).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
权限校验 结合Vue路由实现权限控制。
function checkPermission(roles, routeRoles) {
if (!routeRoles) return true;
return roles.some(role => routeRoles.includes(role));
}
其他实用封装
文件下载 处理浏览器文件下载操作。
function downloadFile(content, fileName) {
const blob = new Blob([content]);
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
URL.revokeObjectURL(link.href);
}
颜色转换 实现HEX与RGB颜色格式互转。
function hexToRgb(hex) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return `rgb(${r}, ${g}, ${b})`;
}
小结
- 日期处理、防抖节流、存储操作等方法应优先封装。
- 通过插件机制全局注册,避免重复导入。
- 深拷贝、金额格式化等工具函数需注意边界条件处理。
更多推荐

所有评论(0)