53 lines
1.0 KiB
TypeScript
53 lines
1.0 KiB
TypeScript
|
|
/*
|
||
|
|
* @Author: 田鑫
|
||
|
|
* @Date: 2024-06-11 14:55:40
|
||
|
|
* @LastEditors: 田鑫
|
||
|
|
* @LastEditTime: 2024-06-11 14:55:41
|
||
|
|
* @Description:
|
||
|
|
*/
|
||
|
|
|
||
|
|
|
||
|
|
/**
|
||
|
|
* @description 模拟的react的useEffect
|
||
|
|
* @param fn
|
||
|
|
* @param deps
|
||
|
|
*/
|
||
|
|
export function useEffect(fn: () => void | (() => any), deps: any[] = []) {
|
||
|
|
const tract = new Error();
|
||
|
|
const resFn = ref(() => { });
|
||
|
|
if (deps.length === 0) {
|
||
|
|
onMounted(() => {
|
||
|
|
const res = fn();
|
||
|
|
if (typeof res === 'function') {
|
||
|
|
resFn.value = res;
|
||
|
|
} else {
|
||
|
|
resFn.value = () => { };
|
||
|
|
}
|
||
|
|
});
|
||
|
|
} else {
|
||
|
|
watch(
|
||
|
|
() => deps,
|
||
|
|
() => {
|
||
|
|
resFn.value();
|
||
|
|
const res = (() => {
|
||
|
|
try {
|
||
|
|
return fn();
|
||
|
|
} catch (error) {
|
||
|
|
console.error(tract);
|
||
|
|
console.error(error);
|
||
|
|
}
|
||
|
|
})();
|
||
|
|
if (typeof res === 'function') {
|
||
|
|
resFn.value = res;
|
||
|
|
} else {
|
||
|
|
resFn.value = () => { };
|
||
|
|
}
|
||
|
|
},
|
||
|
|
{ immediate: true, deep: true },
|
||
|
|
);
|
||
|
|
}
|
||
|
|
onUnmounted(() => {
|
||
|
|
resFn.value();
|
||
|
|
});
|
||
|
|
}
|