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>
相关推荐
做前端的娜娜子16 小时前
同一链接实现 PC Web 与移动 H5 自适应
前端·掘金·金石计划
小帅不太帅16 小时前
架构没变、规模没变,DeepSeek V4 Flash 正式版凭什么暴涨 47 分?
前端·aigc·deepseek
jarvisuni16 小时前
DeepSeekFlash前端依旧拉垮,而且变慢了很多!
前端·javascript·算法
卷福同学17 小时前
AI编程出海第二步:验证关键词能否做站
前端·人工智能·后端
赵庆明老师18 小时前
Vben精讲:21-详解web-antd:tsconfig.json
前端·json·vim
wc8818 小时前
微软EDGE浏览器功能学习
前端·学习·edge
破z晓18 小时前
javascript 导出excel表
开发语言·javascript·excel
Csvn18 小时前
🎯 原生 `<dialog>` 元素:终于可以扔掉一半的自定义弹窗组件了?
前端
Csvn18 小时前
🎨 CSS @layer:用「层叠优先级」终结样式打架的世纪难题
前端