vue实现pwa
使用 Vue CLI 实现 PWA
Vue CLI 内置了 PWA 插件(@vue/cli-plugin-pwa),可以快速将 Vue 项目转换为 PWA。以下是具体实现步骤:
安装 Vue CLI(如已安装可跳过):
npm install -g @vue/cli
创建 Vue 项目:
vue create my-pwa-app
添加 PWA 插件:
vue add pwa
配置 PWA 参数
在 vue.config.js 中配置 PWA 选项:
module.exports = {
pwa: {
name: 'My PWA App',
themeColor: '#4DBA87',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
workboxPluginMode: 'GenerateSW',
workboxOptions: {
skipWaiting: true,
clientsClaim: true,
}
}
}
注册 Service Worker
在 main.js 中注册 Service Worker:
import { register } from 'register-service-worker'
if (process.env.NODE_ENV === 'production') {
register(`${process.env.BASE_URL}service-worker.js`, {
ready() {
console.log('App is being served from cache by a service worker.')
},
registered() {
console.log('Service worker has been registered.')
},
cached() {
console.log('Content has been cached for offline use.')
},
updatefound() {
console.log('New content is downloading.')
},
updated() {
console.log('New content is available; please refresh.')
},
offline() {
console.log('No internet connection found. App is running in offline mode.')
},
error(error) {
console.error('Error during service worker registration:', error)
}
})
}
创建 Manifest 文件
在 public 目录下创建 manifest.json:
{
"name": "My PWA App",
"short_name": "PWA",
"theme_color": "#4DBA87",
"background_color": "#ffffff",
"display": "standalone",
"scope": "/",
"start_url": "/",
"icons": [
{
"src": "img/icons/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
},
{
"src": "img/icons/android-chrome-512x512.png",
"sizes": "512x512",
"type": "image/png"
}
]
}
添加离线提示
在 App.vue 中添加离线状态检测:
mounted() {
window.addEventListener('online', this.updateOnlineStatus)
window.addEventListener('offline', this.updateOnlineStatus)
},
methods: {
updateOnlineStatus() {
this.isOnline = navigator.onLine
if (!this.isOnline) {
// 显示离线提示
}
}
}
构建和部署
构建生产环境版本:
npm run build
部署生成的 dist 目录到支持 HTTPS 的服务器,PWA 需要 HTTPS 才能正常工作。
测试 PWA 功能
使用 Lighthouse 工具测试 PWA 功能:
- 在 Chrome 中打开开发者工具
- 切换到 Lighthouse 标签
- 勾选 PWA 选项
- 运行测试
高级配置选项
对于更高级的缓存策略,可以修改 workboxOptions:

workboxOptions: {
runtimeCaching: [
{
urlPattern: /^https:\/\/api\.example\.com\/.*/,
handler: 'NetworkFirst',
options: {
cacheName: 'api-cache',
expiration: {
maxEntries: 10,
maxAgeSeconds: 60 * 60 * 24 // 1 day
}
}
}
]
}






