import storageUtil from "@utility/storageUtil.js"; import commonUtil from "@utility/commonUtil.js"; import {onActivated, onDeactivated, onMounted} from "vue"; /** * @method useLifecycle 组件生命周期 * @param option {Object} 生命周期配置 * @property init {Function} 初始化函数,组件初始化时调用 * @property load {Function} 加载函数,组件初始化和激活时调用 * @property unLoad {Function} 卸载函数,组件卸载时调用 * */ const useLifecycle = (option)=>{ onMounted(() => { if(commonUtil.isFun(option.init)) option.init(); }) onActivated(()=>{ if(commonUtil.isFun(option.load)) option.load(); }); onDeactivated(()=>{ if(commonUtil.isFun(option.unLoad)) option.unLoad(); }); }; /** * @method useDebounce 防抖hook,多次频繁操作以最后一次为准 * @param fn {Function} 函数 * @param delay {Number} 延时时间 * @returns {Function} * */ const useDebounce = (fn, delay = 300) => { let timer = null return (...args) => { clearTimeout(timer) timer = setTimeout(() => { fn.call(this, ...args) }, delay); } }; /** * @method useThrottle 节流hook,多次频繁操作只会执行一次 * @param fn {Function} 函数 * @param delay {Number} 延时时间 * @returns {Function} * */ const useThrottle = (fn, delay = 300) => { let timer = null return (...args) => { if (!timer) { timer = setTimeout(() => { fn.apply(this, args); clearTimeout(timer) timer = null; }, delay); } }; }; /** * @method useGetJsonDeepValue 获取多级json值 * @param obj {Object} json对象 * @param key {String} 获取值的可以,如:key.key1 * @returns {String} 返回获取道的json值 * */ const useGetJsonDeepValue = (obj, key) => { if (!commonUtil.isJson(obj) || !key) return; let keyArray = ''; let value = key; if (commonUtil.isStr(key)) { keyArray = key.split('.'); value = obj[keyArray[0]]; if (keyArray.length > 1) { for (let index = 1; index < keyArray.length; index++) { if (!value) break; value = value[keyArray[index]]; } } } return value; } /** * @method manualCopying 手动复制对象 * @param value {Object} 待复制对象 * @returns {Object} 复制后的对象 * */ const manualCopying = (value) => { return JSON.parse(JSON.stringify(value)) } /** * @method useEnv 获取env变量 * @returns {Object} 转换后的值 * */ const useEnv = () => { const env = import.meta.env; return { nodeEnv: env.VITE_NODE_ENV, baseUrl: env.VITE_BASE_URL, fileUrl: env.VITE_FILE_URL, dateFormat: env.VITE_DATE_FORMAT } }; export { useDebounce, useThrottle, useGetJsonDeepValue, useEnv, useLifecycle, manualCopying }