Vue實現(xiàn)前端頁面版本檢測的示例代碼
為什么需要版本檢測
1. 解決瀏覽器緩存問題
- 靜態(tài)資源緩存:瀏覽器會緩存 JS、CSS 等靜態(tài)資源,用戶可能繼續(xù)使用舊版本
- 用戶體驗影響:用戶無法及時獲取新功能,導(dǎo)致功能缺失或操作異常
2. 保障功能一致性
- 功能同步:確保所有用戶都能使用最新的功能和修復(fù)
- 數(shù)據(jù)一致性:避免因版本差異導(dǎo)致的數(shù)據(jù)不一致問題
3. 提升用戶體驗
- 主動提醒:在新版本發(fā)布后主動通知用戶更新
- 無縫升級:減少用戶手動刷新頁面的需求
版本檢測核心思路

整體架構(gòu)
構(gòu)建階段 → 版本文件生成 → 運行時檢測 → 版本對比 → 用戶提醒
技術(shù)實現(xiàn)要點
1. 版本標識生成
- 構(gòu)建時生成:每次打包時生成唯一的版本標識
- 時間戳方案:使用時間戳確保每次構(gòu)建版本號唯一
2. 版本文件部署
- JSON 格式:將版本信息保存為
version.json文件 - 靜態(tài)訪問:通過 HTTP 請求可直接訪問版本文件
3. 客戶端檢測機制
- 定時輪詢:定期檢查服務(wù)器版本文件
- 版本對比:比較本地緩存版本與服務(wù)器版本
- 智能提醒:僅在版本不一致時提醒用戶
版本檢測實現(xiàn)步驟
步驟一:構(gòu)建版本文件生成腳本
創(chuàng)建 build-version.js 文件:
// build-version.js (自動生成版本文件腳本)
const fs = require('fs')
const path = require('path')
// 方案A:使用時間戳作為版本標識(最簡單,確保每次打包唯一)
const version = new Date().getTime().toString()
// 版本文件內(nèi)容
const versionJson = {
version: version,
updateTime: new Date().toLocaleString() // 可選:添加更新時間,便于排查
}
// 寫入version.json文件(項目根目錄)
const versionPath = path.resolve(__dirname, 'public', 'version.json')
fs.writeFileSync(versionPath, JSON.stringify(versionJson, null, 2), 'utf-8')
console.log(`? 自動生成版本文件成功,版本號:${version}`)
步驟二:修改構(gòu)建命令
在 package.json 中修改構(gòu)建命令:
{
"scripts": {
"build:prod": "node build-version.js && vue-cli-service build"
}
}
步驟三:配置 Vue 構(gòu)建過程
在 vue.config.js 中添加版本文件復(fù)制配置:
chainWebpack(config) {
// ... 其他配置
// 復(fù)制 version.json 到 dist 目錄
config.plugin('copy')
.tap(args => {
const hasVersionJson = args[0].some(item => item.from === 'version.json')
if (!hasVersionJson) {
args[0].push({
from: path.resolve(__dirname, 'public/version.json'),
to: path.resolve(__dirname, 'dist/version.json')
})
}
return args
})
}
步驟四:實現(xiàn)版本檢測工具類
創(chuàng)建 src/utils/versionUpdate.js:
// src/utils/versionUpdate.js
import { Notification } from 'element-ui'
/**
* 版本更新檢測工具類(僅生產(chǎn)環(huán)境啟用輪詢,內(nèi)置環(huán)境判斷)
*/
class VersionUpdate {
constructor(options = {}) {
this.config = {
versionFileUrl: '/version.json', // 版本文件地址
localVersionKey: 'cmpVersion', // 本地存儲的版本號key
disableFetchCache: true, // 禁用Fetch緩存
pollInterval: 5 * 60 * 1000, // 5分鐘輪詢一次
hasNotified: false // 是否已提醒過用戶有新版本
}
Object.assign(this.config, options)
// 定時輪詢定時器
this.pollTimer = null
// 識別當前環(huán)境(Vue CLI 4 自動注入的環(huán)境變量)
this.isProduction = process.env.NODE_ENV === 'production'
}
/**
* 核心方法:執(zhí)行版本檢測
*/
async checkVersion(isInit = false) {
try {
if (this.config.hasNotified) return false
const localVersion = localStorage.getItem(this.config.localVersionKey) || ''
const fetchOptions = {}
if (this.config.disableFetchCache) {
fetchOptions.cache = 'no-cache'
}
const response = await fetch(this.config.versionFileUrl, fetchOptions)
if (!response.ok) {
throw new Error(`版本文件請求失敗,狀態(tài)碼:${response.status}`)
}
const latestVersionInfo = await response.json()
const serverVersion = latestVersionInfo.version
if (isInit) {
this.cacheLatestVersion(serverVersion)
return true
}
if (serverVersion && serverVersion !== localVersion) {
this.config.hasNotified = true
console.log('有新版本可用', latestVersionInfo)
Notification({
title: '?? 有新版本可用',
dangerouslyUseHTMLString: true,
message: `<p style="font-size:12px;">建議點擊刷新頁面,以獲取最新功能和修復(fù)</p> <p style="color:#cccccc;font-size:12px;">更新時間:${latestVersionInfo.updateTime}</p>`,
duration: 0,
customClass: 'check-version-notify',
onClick: () => {
this.forceRefreshPage()
},
onClose: () => {
this.resetNotifyFlag()
}
})
return true
} else {
// 版本一致時,重置提醒標記,便于后續(xù)輪詢檢測新版本
this.config.hasNotified = false
// console.log('當前已是最新版本,已緩存最新版本號')
return false
}
} catch (error) {
console.warn('版本檢測異常,不影響應(yīng)用運行:', error.message)
return false
}
}
/**
* 啟動定時輪詢檢測(內(nèi)置環(huán)境判斷:僅生產(chǎn)環(huán)境生效)
*/
async startPolling() {
// 核心:非生產(chǎn)環(huán)境,直接返回,不啟動輪詢
if (!this.isProduction) {
console.log('當前為非生產(chǎn)環(huán)境,不啟動版本檢測輪詢')
return
}
// 生產(chǎn)環(huán)境:正常啟動輪詢
this.stopPolling() // 先停止已有輪詢,避免重復(fù)啟動
this.checkVersion(true) // 立即執(zhí)行一次檢測
this.pollTimer = setInterval(() => {
this.checkVersion()
}, this.config.pollInterval)
console.log(`生產(chǎn)環(huán)境版本輪詢檢測已啟動,每隔${this.config.pollInterval / 1000 / 60}分鐘檢測一次`)
}
/**
* 停止定時輪詢檢測
*/
stopPolling() {
if (this.pollTimer) {
clearInterval(this.pollTimer)
this.pollTimer = null
console.log('版本輪詢檢測已停止')
}
}
/**
* 重置提醒標記
*/
resetNotifyFlag() {
this.config.hasNotified = false
}
// 緩存最新版本號
cacheLatestVersion(version) {
localStorage.setItem(this.config.localVersionKey, version)
this.resetNotifyFlag()
}
// 強制刷新頁面
forceRefreshPage() {
window.location.reload(true)
}
}
const versionUpdateInstance = new VersionUpdate()
export { VersionUpdate, versionUpdateInstance }
export default versionUpdateInstance
創(chuàng)建自定義.check-version-notify的版本檢測全局樣式:

// 版本檢測通知樣式
.check-version-notify{
border: 3px solid transparent !important;
cursor: pointer;
background-color: rgba(255, 255, 255, 0.6) !important;
backdrop-filter: blur(5px);
&:hover{
border: 3px solid $--color-primary !important;
}
.el-notification__icon{
font-size: 18px;
height: 18px;
}
.el-notification__title{
font-size: 14px;
line-height: 18px;
}
.el-notification__group{
margin-left: 8px;
}
}
步驟五:在應(yīng)用入口啟動版本檢測
在 App.vue 或合適的入口文件中啟動版本檢測:
import versionUpdate from '@/utils/versionUpdate'
...
mounted() {
versionUpdate.startPolling()
},
beforeDestroy() {
versionUpdate.stopPolling()
}
到此這篇關(guān)于Vue實現(xiàn)前端頁面版本檢測的示例代碼的文章就介紹到這了,更多相關(guān)Vue頁面版本檢測內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue 在methods中調(diào)用mounted的實現(xiàn)操作
這篇文章主要介紹了vue 在methods中調(diào)用mounted的實現(xiàn)操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-08-08
Vite模塊動態(tài)導(dǎo)入之Glob導(dǎo)入實踐
import.meta.glob是Vite提供的強大模塊動態(tài)導(dǎo)入功能,用于在構(gòu)建時批量導(dǎo)入模塊并生成按需加載的代碼,適用于處理大量文件2026-01-01
vue單頁面實現(xiàn)當前頁面刷新或跳轉(zhuǎn)時提示保存
這篇文章主要介紹了vue單頁面實現(xiàn)當前頁面刷新或跳轉(zhuǎn)時提示保存,在當前頁面刷新或跳轉(zhuǎn)時提示保存并可取消刷新,以防止填寫的表單內(nèi)容丟失,感興趣的小伙伴們可以參考一下2018-11-11
使用vue ant design分頁以及表格分頁改為中文問題
這篇文章主要介紹了使用vue ant design分頁以及表格分頁改為中文問題,具有很好的參考價值,希望對大家有所幫助。2023-04-04
vue3動態(tài)路由+動態(tài)組件+緩存應(yīng)用方式
這篇文章主要介紹了vue3動態(tài)路由+動態(tài)組件+緩存應(yīng)用方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04

