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>
相关推荐
kyriewen26 分钟前
白宫直接给 OpenAI 下了限制令,GPT-5.6 不能随便放出来了
前端·javascript·面试
PedroQue991 小时前
Vite插件v0.2.6:架构优化与自动化升级
前端·vite
threerocks3 小时前
什么?我连 A2A、MCP 都没学会,现在又来了 AG-UI、A2UI.
前端·aigc·ai编程
牛奶3 小时前
如何自己写一个浏览器插件?
前端·chrome·浏览器
亿元程序员4 小时前
为什么Cocos都4.0了还有人用2.x?
前端
MomentYY4 小时前
AI 到底是“懂”,还是在“猜”?
前端·人工智能·ai编程
鹏毓网络科技4 小时前
Cursor Rules 文件配置实战:3 个隐藏参数让我每月少写 40% 样板代码
前端·github
没烦恼3014 小时前
无痕模式下 HTTP\-First 拦截引发的“页面刷新”误判
前端
ZhengEnCi4 小时前
Q02-Vue-React-index.html完全指南
vue.js·react.js·html
文心快码BaiduComate4 小时前
从个人提效到组织提效:Comate辅助构建自我进化的AI研发系统
前端·程序员