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>
相关推荐
ᅠᅠᅠ@几秒前
异常枚举;
开发语言·javascript·ecmascript
小阿飞_1 分钟前
报错合计-1
前端
caperxi3 分钟前
前端开发中的防抖与节流
前端·javascript·html
霸气小男3 分钟前
react + antDesign封装图片预览组件(支持多张图片)
前端·react.js
susu10830189114 分钟前
前端css样式覆盖
前端·css
学习路上的小刘5 分钟前
vue h5 蓝牙连接 webBluetooth API
前端·javascript·vue.js
&白帝&5 分钟前
vue3常用的组件间通信
前端·javascript·vue.js
小白小白从不日白16 分钟前
react 组件通讯
前端·react.js
罗_三金27 分钟前
前端框架对比和选择?
javascript·前端框架·vue·react·angular
Redstone Monstrosity33 分钟前
字节二面
前端·面试