vue3提示用戶版本更新方式
更新時間:2024年12月26日 14:56:00 作者:張小偉i
本文介紹了如何在項(xiàng)目中創(chuàng)建和使用自定義插件,以在構(gòu)建過程中檢查版本號,具體步驟包括在項(xiàng)目根目錄下創(chuàng)建buildLifeHook.ts文件,并在public目錄下創(chuàng)建version文件夾,然后在vite.config.ts中引用該插件,并在src/utils目錄下創(chuàng)建XxzUtils.ts文件
vue3提示用戶版本更新
1.項(xiàng)目根目錄下創(chuàng)建myPlugins/buildLifeHook.ts
在public下創(chuàng)建version文件夾
- buildLifeHook.ts代碼
import fs from 'fs'; import path from 'path'; // 在Vite配置中添加一個插件,監(jiān)聽build事件 export function buildLifeHook() { return { name: 'build-life-hook', buildStart(){ let now = new Date().toLocaleString().replace(/\//g,'-') let version = { version:now, } let versionPath = path.join(__dirname,'../public/version/versionData.json'); fs.writeFile(versionPath,JSON.stringify(version),'utf8',(err)=>{ if(err){ console.log('寫入文件失敗',err); }else{ console.log('寫入文件成功'); } }) // console.log('構(gòu)建開始!' + now); }, buildEnd() { let now = new Date().toLocaleString().replace(/\//g,'-') // console.log('構(gòu)建完成!' + now); }, }; }
2.在vite.config.ts中引用插件
3.在src/utils下創(chuàng)建XxzUtils.ts
- XxzUtils.ts中代碼
/** * 版本更新 */ /** * @description 檢測版本更新 * @param allowIgnore 是否允許忽略 * @param timer 傳入定時器 * @returns */ export async function checkUpdate(allowIgnore: boolean, timer?: any) { //動態(tài)獲取線上的資源地址,其實(shí)就是vite.config.ts的base的值 try { // 檢測前端資源是否有更新 let response = await fetch(`/version/versionData.json`, { headers: { 'Cache-Control': 'no-cache' } }).then(res => res.json()) if (!localStorage.getItem('JHS_version')) { localStorage.setItem('JHS_version', response.version) } else { if (localStorage.getItem('JHS_version') !== response.version) { if (versionUpdateTimer != null) { clearInterval(versionUpdateTimer) } ElMessageBox.confirm( '是否刷新頁面重新加載最新版?', '檢測到新版本', { confirmButtonText: '好的', cancelButtonText: '不了', type: 'warning', showClose: false, closeOnClickModal: false } ) .then(() => { localStorage.setItem('JHS_version', response.version) window.location.reload() }) } } } catch (e) { return Promise.reject(e) } } /** * @description 初始化版本檢測器 */ let versionUpdateTimer = null export function initVersionCheck() { versionUpdateTimer = setInterval(() => { checkUpdate(true, versionUpdateTimer).then(r => null) }, 60000) }
4.在App.vue文件下調(diào)用initVersionCheck()方法
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于Vue Router的10條高級技巧總結(jié)
這篇文章主要給大家總結(jié)介紹了關(guān)于Vue Router的10條高級技巧,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-05-05Vue.js頁面驗(yàn)證跳轉(zhuǎn)功能實(shí)現(xiàn)
這篇文章主要介紹了Vue.js頁面驗(yàn)證跳轉(zhuǎn)功能實(shí)現(xiàn),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-04-04vue-cli腳手架創(chuàng)建項(xiàng)目遇到的坑及解決
這篇文章主要介紹了vue-cli腳手架創(chuàng)建項(xiàng)目遇到的坑及解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-01-01Vue3+ElementPlus封裝圖片空間組件的門面實(shí)例
圖片空間是用于管理上傳圖片的工具,可以讓用戶方便地存儲、管理和調(diào)用圖片,提高工作效率,它通常具備多樣的樣式,但操作入口統(tǒng)一,便于使用,通過圖片空間組件,用戶能直接在其他模塊(例如商品圖片)中選擇所需圖片2024-09-09