vite vue3 pwa 更新提醒

效果

vite-plugin-pwa插件启用pwa后默认会在后台自动更新应用,并在关闭所有已开启的页面并重新打开后激活

通过此方法可以以消息方式提醒用户手动刷新激活更新应用

方法

已经使用vite-plugin-pwa插件启用pwa

  • 修改vite.config.ts
ts 复制代码
export default defineConfig({
	...
	plugins: [
		...
		VitePWA({
			// 修改此项,如果此项值为autoUpdate,则为自动给更新
			registerType: "prompt",
		}),
		...
	],
	...
})
  • 创建提醒组件
html 复制代码
<script setup lang="ts">
import {useRegisterSW} from 'virtual:pwa-register/vue'
import {ElButton} from "element-plus"
import "element-plus/es/components/button/style/css"

const {
  offlineReady,
  needRefresh,
  updateServiceWorker,
} = useRegisterSW({
  immediate: true,
  onRegisteredSW(swUrl, r) {
    r && setInterval(async () => {
      // 检查更新,如果vite.config.ts配置为autoUpdate,此操作将直接触发更新,并刷新页面激活更新
      await r.update()
    }, 30000)
  },
})

async function close() {
  offlineReady.value = false
  needRefresh.value = false
}
</script>

<template>
  <div
      class="pwa-toast"
      role="alert"
  >
    <div class="message">
      <span v-if="offlineReady">
        应用已就绪
      </span>
      <span v-else>
        新内容可用,点击重新加载按钮以更新。
      </span>
    </div>
    <el-button
        type="primary"
        @click="updateServiceWorker()"
    >
      重新加载
    </el-button>
    <el-button @click="close">
      关闭
    </el-button>
  </div>
</template>

<style scoped>
.pwa-toast {
  position: fixed;
  right: 0;
  bottom: 0;
  margin: 16px;
  padding: 12px;
  border: 1px solid #8885;
  border-radius: 4px;
  z-index: 1;
  text-align: left;
  box-shadow: 3px 4px 5px 0px #8885;
  background-color: var(--el-bg-color);
}

.pwa-toast .message {
  margin-bottom: 8px;
}
</style>
  • 在应用中引入提醒组件
    App.vue
html 复制代码
<script setup lang="ts">
import {ElConfigProvider} from 'element-plus'
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import ReloadPrompt from "./components/ReloadPrompt.vue";
</script>

<template>
  <el-config-provider :locale="zhCn">
    ...
    <reload-prompt/>
  </el-config-provider>
</template>
相关推荐
Aric_Jones7 小时前
JavaScript 从入门到精通:完整语法指南
开发语言·javascript·ecmascript
岱宗夫up7 小时前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
紫陌涵光7 小时前
112. 路径总和
java·前端·算法
漠月瑾-西安7 小时前
CVE-2025-55182漏洞解析:你的React项目安全吗?
前端·安全·react.js
No丶slovenly8 小时前
flutter笔记-输入框
前端·笔记·flutter
国产化创客8 小时前
ESP32+Web实现智能气象站
前端·物联网·智能家居·智能硬件
coderYYY9 小时前
VSCode终端启动报错
前端·ide·vscode·npm·编辑器
西门吹-禅9 小时前
文本搜索node js--meilisearch
开发语言·javascript·ecmascript
tod11310 小时前
Redis 数据类型与 C++ 客户端实践指南(redis-plus-plus)
前端·c++·redis·bootstrap·html
Sylvia33.10 小时前
火星数据:棒球数据API
java·前端·人工智能