import { onMounted, ref } from "vue"; export function usePWAInstall() { const deferredPrompt = ref(null); const canInstall = ref(false); const isInstalled = ref(false); onMounted(() => { // 检查是否已安装 if (window.matchMedia("(display-mode: standalone)").matches) { isInstalled.value = true; return; } // 监听安装提示事件 window.addEventListener("beforeinstallprompt", (e) => { e.preventDefault(); deferredPrompt.value = e; canInstall.value = true; }); // 监听安装成功事件 window.addEventListener("appinstalled", () => { deferredPrompt.value = null; canInstall.value = false; isInstalled.value = true; }); }); async function install() { if (!deferredPrompt.value) { return false; } try { await deferredPrompt.value.prompt(); const { outcome } = await deferredPrompt.value.userChoice; if (outcome === "accepted") { deferredPrompt.value = null; canInstall.value = false; return true; } return false; } catch (error) { console.error("安装失败:", error); return false; } } return { canInstall, isInstalled, install, }; }