feat: 添加 PWA 安装支持,包括安装横幅和按钮;更新国际化文本;配置 PWA 清单和缓存策略

This commit is contained in:
2026-01-05 15:49:35 +07:00
parent ee997fd612
commit 01e727490c
10 changed files with 332 additions and 4 deletions

View File

@@ -2,6 +2,7 @@
<template>
<UApp>
<NuxtPwaManifest />
<NuxtPage />
</UApp>
</template>

View File

@@ -0,0 +1,117 @@
<script setup lang="ts">
const { t } = useI18n()
const { canInstall, isInstalled, install } = usePWAInstall()
const installing = ref(false)
const dismissed = ref(false)
// 从 localStorage 读取是否已关闭,但只在未安装状态下有效
onMounted(() => {
// 如果应用未安装,检查用户是否之前关闭过横幅
if (!isInstalled.value) {
dismissed.value = localStorage.getItem('pwa-banner-dismissed') === 'true'
}
else {
// 如果应用已安装,清除关闭记录(为了卸载后能再次提示)
localStorage.removeItem('pwa-banner-dismissed')
}
})
// 监听安装状态变化
watch(isInstalled, (newValue) => {
if (newValue) {
// 应用安装后,清除关闭记录
localStorage.removeItem('pwa-banner-dismissed')
dismissed.value = false
}
})
// 监听 canInstall 变化(卸载后会重新触发 beforeinstallprompt
watch(canInstall, (newValue) => {
if (newValue && !isInstalled.value) {
// 如果可以安装且未安装,清除之前的关闭记录
// 这样卸载后再次访问就会重新显示横幅
localStorage.removeItem('pwa-banner-dismissed')
dismissed.value = false
}
})
async function handleInstall() {
installing.value = true
try {
const success = await install()
if (success) {
console.log('PWA 安装成功')
}
}
finally {
installing.value = false
}
}
function dismissBanner() {
dismissed.value = true
localStorage.setItem('pwa-banner-dismissed', 'true')
}
const showBanner = computed(() => canInstall.value && !isInstalled.value && !dismissed.value)
</script>
<template>
<Transition
enter-active-class="transition-all duration-300 ease-out"
enter-from-class="opacity-0 transform translate-y-4"
enter-to-class="opacity-100 transform translate-y-0"
leave-active-class="transition-all duration-200 ease-in"
leave-from-class="opacity-100 transform translate-y-0"
leave-to-class="opacity-0 transform translate-y-4"
>
<UCard
v-if="showBanner"
class="relative overflow-hidden border-2 border-primary-500/20 shadow-xl shadow-primary-500/10"
>
<!-- 背景装饰 -->
<div class="absolute inset-0 bg-linear-to-br from-primary-50/80 via-blue-50/50 to-purple-50/80 dark:from-primary-950/50 dark:via-blue-950/30 dark:to-purple-950/50" />
<div class="absolute top-0 right-0 w-64 h-64 bg-primary-500/10 rounded-full blur-3xl" />
<div class="absolute bottom-0 left-0 w-64 h-64 bg-purple-500/10 rounded-full blur-3xl" />
<!-- 内容 -->
<div class="relative z-10 flex items-center gap-4">
<!-- 图标 -->
<div class="hidden sm:flex flex-shrink-0 size-16 rounded-2xl bg-linear-to-br from-primary-500 to-primary-600 items-center justify-center text-white text-2xl font-bold shadow-lg shadow-primary-500/30">
<UIcon name="i-heroicons-arrow-down-tray" class="w-8 h-8" />
</div>
<!-- 文字内容 -->
<div class="flex-1 min-w-0">
<h3 class="text-lg font-bold text-gray-900 dark:text-white mb-1">
{{ t('installPWA') }}
</h3>
<p class="text-sm text-gray-600 dark:text-gray-400">
{{ t('installDesc') }}
</p>
</div>
<!-- 按钮组 -->
<div class="flex items-center gap-2 flex-shrink-0">
<UButton
:loading="installing"
size="lg"
color="primary"
icon="i-heroicons-arrow-down-tray"
class="shadow-lg shadow-primary-500/30"
@click="handleInstall"
>
{{ t('installPWA') }}
</UButton>
<UButton
icon="i-heroicons-x-mark"
color="neutral"
variant="ghost"
size="lg"
@click="dismissBanner"
/>
</div>
</div>
</UCard>
</Transition>
</template>

View File

@@ -0,0 +1,42 @@
<script setup lang="ts">
const { t } = useI18n()
const { canInstall, isInstalled, install } = usePWAInstall()
const installing = ref(false)
async function handleInstall() {
installing.value = true
try {
const success = await install()
if (success) {
// 可以显示成功提示
console.log('PWA 安装成功')
}
}
finally {
installing.value = false
}
}
</script>
<template>
<UButton
v-if="canInstall && !isInstalled"
:loading="installing"
size="md"
icon="i-heroicons-arrow-down-tray"
@click="handleInstall"
>
{{ t('installPWA') }}
</UButton>
<UBadge
v-else-if="isInstalled"
size="md"
color="primary"
variant="subtle"
>
<div class="flex items-center gap-2">
<UIcon name="i-heroicons-check-circle" class="w-5 h-5" />
{{ t('installed') }}
</div>
</UBadge>
</template>

View File

@@ -0,0 +1,58 @@
import { ref, onMounted } from 'vue'
export function usePWAInstall() {
const deferredPrompt = ref<any>(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,
}
}

View File

@@ -13,5 +13,8 @@
"iosDownloads": "iOS Downloads",
"androidDownloads": "Android Downloads",
"noAppsFound": "No apps found",
"downloadApp": "Download App"
"downloadApp": "Download App",
"installPWA": "Install App Store",
"installed": "Installed",
"installDesc": "Install on your home screen and use it like a native app"
}

View File

@@ -13,5 +13,8 @@
"iosDownloads": "iOS 下载",
"androidDownloads": "Android 下载",
"noAppsFound": "没有找到应用",
"downloadApp": "下载应用"
"downloadApp": "下载应用",
"installPWA": "安装应用商店",
"installed": "已安装",
"installDesc": "安装到主屏幕,像原生应用一样使用"
}

View File

@@ -4,10 +4,84 @@ export default defineNuxtConfig({
'@nuxt/ui',
'@nuxtjs/i18n',
'@nuxt/eslint',
'@vite-pwa/nuxt',
],
devtools: { enabled: true },
pwa: {
registerType: 'autoUpdate',
manifest: {
name: 'Riwa App 下载',
short_name: 'Riwa应用商店',
description: 'Riwa App 下载 - iOS, Android, H5',
theme_color: '#3b82f6',
background_color: '#ffffff',
display: 'standalone',
scope: '/',
start_url: '/',
icons: [
{
src: '/favicon.svg',
sizes: '512x512',
type: 'image/svg+xml',
purpose: 'any',
},
{
src: '/favicon.svg',
sizes: '192x192',
type: 'image/svg+xml',
},
],
},
workbox: {
navigateFallback: '/',
globPatterns: ['**/*.{js,css,html,png,svg,ico}'],
cleanupOutdatedCaches: true,
runtimeCaching: [
{
urlPattern: /^https:\/\/fonts\.googleapis\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'google-fonts-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 365, // 1 year
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
{
urlPattern: /^https:\/\/fonts\.gstatic\.com\/.*/i,
handler: 'CacheFirst',
options: {
cacheName: 'gstatic-fonts-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 * 365, // 1 year
},
cacheableResponse: {
statuses: [0, 200],
},
},
},
],
},
client: {
installPrompt: true,
periodicSyncForUpdates: 3600,
},
devOptions: {
enabled: true,
type: 'module',
},
injectManifest: {
globPatterns: ['**/*.{js,css,html,png,svg,ico}'],
},
},
css: [
'~/assets/css/main.css',
'~/assets/css/animations.css',

View File

@@ -9,7 +9,7 @@
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare",
"deploy": "pnpx wrangler pages deploy dist --project-name=appstore --branch=main"
"deploy": "pnpx wrangler pages deploy .output/public --project-name=appstore --branch=main"
},
"dependencies": {
"@nuxt/ui": "^4.3.0",
@@ -18,6 +18,7 @@
},
"devDependencies": {
"@nuxt/eslint": "^1.12.1",
"@vite-pwa/nuxt": "^1.1.0",
"typescript": "~5.9.3"
}
}

View File

@@ -137,7 +137,12 @@ useHead({
</UContainer>
<!-- Main Content -->
<UContainer class="py-8">
<UContainer>
<!-- PWA Install Banner -->
<div class="mb-6">
<PWAInstallBanner />
</div>
<!-- Search and Filter -->
<div class="mb-8 space-y-4">
<!-- Search -->

24
pnpm-lock.yaml generated
View File

@@ -250,6 +250,9 @@ importers:
'@nuxt/eslint':
specifier: ^1.12.1
version: 1.12.1(@typescript-eslint/utils@8.49.0(eslint@9.39.1(jiti@2.6.1))(typescript@5.9.3))(@vue/compiler-sfc@3.5.25)(eslint-plugin-format@1.1.0(eslint@9.39.1(jiti@2.6.1)))(eslint@9.39.1(jiti@2.6.1))(magicast@0.5.1)(typescript@5.9.3)(vite@7.2.7(@types/node@24.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(yaml@2.8.2))
'@vite-pwa/nuxt':
specifier: ^1.1.0
version: 1.1.0(magicast@0.5.1)(vite@7.2.7(@types/node@24.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(yaml@2.8.2))(workbox-build@7.4.0)(workbox-window@7.4.0)
typescript:
specifier: ~5.9.3
version: 5.9.3
@@ -3374,6 +3377,14 @@ packages:
engines: {node: '>=18'}
hasBin: true
'@vite-pwa/nuxt@1.1.0':
resolution: {integrity: sha512-OKrqHg9PHCqp9dlrtCaLlh55V0xEG/zkXjvpl2nE+6IB3xW8mqnH0hXYc1pjN7qv0JzB+lbCfWxFsg5EZvAjWA==}
peerDependencies:
'@vite-pwa/assets-generator': ^1.0.0
peerDependenciesMeta:
'@vite-pwa/assets-generator':
optional: true
'@vitejs/plugin-legacy@7.2.1':
resolution: {integrity: sha512-CaXb/y0mlfu7jQRELEJJc2/5w2bX2m1JraARgFnvSB2yfvnCNJVWWlqAo6WjnKoepOwKx8gs0ugJThPLKCOXIg==}
engines: {node: ^20.19.0 || >=22.12.0}
@@ -12359,6 +12370,19 @@ snapshots:
- rollup
- supports-color
'@vite-pwa/nuxt@1.1.0(magicast@0.5.1)(vite@7.2.7(@types/node@24.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(yaml@2.8.2))(workbox-build@7.4.0)(workbox-window@7.4.0)':
dependencies:
'@nuxt/kit': 3.20.2(magicast@0.5.1)
pathe: 1.1.2
ufo: 1.6.1
vite-plugin-pwa: 1.2.0(vite@7.2.7(@types/node@24.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(yaml@2.8.2))(workbox-build@7.4.0)(workbox-window@7.4.0)
transitivePeerDependencies:
- magicast
- supports-color
- vite
- workbox-build
- workbox-window
'@vitejs/plugin-legacy@7.2.1(terser@5.44.1)(vite@7.2.7(@types/node@24.10.2)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.44.1)(yaml@2.8.2))':
dependencies:
'@babel/core': 7.28.5