生产环境上,如果前端代码有更新,客户由于没有刷新浏览器,还是使用的旧版,怎么友好的提示客户有新的版本更新?
这里以 vue3 + ant-design4 为例
先创建一个 hook,useCheckUpdate.js
import axios from 'axios'
import { notification, Button } from 'ant-design-vue'
/**
* 检测是否有版本更新
*/
export function useCheckUpdate () {
let lastModified = null
const key = Date.now()
// 获取服务器上的 index.html 的最后修改时间
async function getLastModified () {
const resp = await axios.get('?r=' + Date.now())
return resp.headers['last-modified']
}
// 通过最后修改时间与内存中的最后修改时间比较,判断是否需要更新
async function needUpdate () {
try {
const modified = await getLastModified()
console.log('check update -> last-modified: ', modified)
if (!lastModified) {
lastModified = modified
return false
}
return lastModified !== modified
} catch (e) {
return false
}
}
function checkUpdate () {
// 轮询检测
setTimeout(async () => {
const hasUpdate = await needUpdate()
if (hasUpdate) {
notification.close(key)
notification.open({
key,
message: '版本更新',
description: '检测到有新版本待更新,是否现在更新?',
duration: 0,
placement: 'bottomRight',
btn: () => h(Button, {
type: 'primary',
size: 'small',
onClick: () => {
window.location.reload()
},
}, '现在更新')
})
} else {
checkUpdate()
}
}, 120000)
}
// 正式环境下才执行版本检测
if (import.meta.env.PROD) {
checkUpdate()
}
}
然后在 App.vue 中使用
// App.vue
<script setup>
import { useCheckUpdate } from './hooks/useCheckUpdate'
// 检测版本更新
useCheckUpdate()
</script>
一个小小有用的功能就完成啦~~
送上框架源码地址:base-backend-static: Vue3 + Vite + pinia + Ant design4 + js + axios + vue router + pnpmhttps://gitee.com/czleing/base-backend-static如果帮到了您,请点赞+关注哦~~