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>
相关推荐
天平9 小时前
油猴脚本创建webworker踩坑记录
前端·javascript·typescript
原则猫10 小时前
前端基础大厦
前端
陈随易12 小时前
编程语言级别的Skill市场,AI Agent 的未来形态
前端·后端·程序员
SoaringHeart12 小时前
Flutter进阶:基于 EasyRefresh 的下拉刷新封装 n_easy_refresh_mixin.dart
前端·flutter
IT_陈寒14 小时前
Vite的热更新突然不香了,排查三小时差点砸键盘
前端·人工智能·后端
子兮曰15 小时前
Agency-Agents 深度解析:400+ AI 专家的"梦之队"如何重塑开发工作流
前端·后端·vibecoding
山河木马15 小时前
渲染管线-计算得到gl_Position(顶点着色器)之后续GPU流程
javascript·webgl·图形学
竹林81815 小时前
用 The Graph 查询链上数据实战:从手搓 RPC 到 Subgraph,我的 NFT 项目数据加载快了 10 倍
前端·javascript
妙码生花16 小时前
从 PHP 到 AI + Golang,程序员自救转型手记(十九):点选验证码代码逐行目检
前端·后端·go
Awu122716 小时前
⚡从零开发 Agent CLI(五)实现一个可治理、可扩展的工具系统
前端·人工智能·claude