// 初始化数据 import type { Ref } from 'vue'; import { onMounted, ref, watch } from 'vue'; // show.value为undefined时,表示是列表的请求数据,在mounted时调用initData方法,否则表示是弹框请求数据,在show.value为true(即打开弹框)时调用initData方法 export function useInitData(reqFun: any, show: Ref = ref(undefined)) { const optionsData: Ref = ref([]); const initData = async () => { try { const res = await reqFun(); optionsData.value = Array.isArray(res) ? res : res; } catch (e) { console.log(e); } }; onMounted(() => { if (show.value == undefined) { initData(); } }); watch( () => show.value, (v: boolean | undefined) => { if (v) { initData(); return; } }, { immediate: true, deep: true }, ); return { optionsData, initData, }; };