自学内容网 自学内容网

vue3 - vue项目自动检测更新

GitHub Demo 地址

在线预览

web项目当页面检测到需要更新,然后弹框提示是否更新(刷新页面)这种可以通过纯前端实现也可以通过接口实现

  • 接口实现:通过调用接口轮询和本地的版本号比较,检查是否需要弹框提示更新
  • 纯前端实现:项目打包时配置一个版本号然后和本地的版本号轮询比较,检查是否需要弹框提示更新

实现方案

当用户在项目所在的页面时轮询请求,然后在离开页面时停止轮询,再次切回来再次启动轮询,
如果超过轮询的最大次数后,停止轮询。
当请求的版本号大于本地的,或者本地版本号为空,则弹框提示需要更新

效果图

请添加图片描述

一、纯前端实现

打包配置版本号

const versionNumber = '1.1.0'

const { dependencies, devDependencies, name, version } = pkg
export const __APP_INFO__ = {
  pkg: { dependencies, devDependencies, name, version },
  lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  checkUpdateVersion: versionNumber
}

vite.config.ts 启用配置

defineConfig {
...
    define: {
      __APP_INFO__: JSON.stringify(__APP_INFO__)
    }
...
}

版本号本地存储和比较

import { setStorage, getStorage } from '@/utils/storage'
import { getCheckUpgrade } from '@/api/auth'
const kCheckUpdateVersion = 'checkUpdateVersion'
const { checkUpdateVersion } = __APP_INFO__

// 方式一: 通过build\info.ts 配置的版本号和本地进行比较
export const checkUpgrade = () => {
  const version = getVersion()
  let needUpgrade = false
  if ((version && version !== checkUpdateVersion) || !version) {
    needUpgrade = true
  }
  return needUpgrade
}

export const getVersion = () => {
  return getStorage(kCheckUpdateVersion)
}

export const setVersion = (newVersion = checkUpdateVersion) => {
  setStorage(kCheckUpdateVersion, newVersion)
}

轮询工具类

let activeCount: number = 0
const MAX_INACTIVE_COUNT: number = 5
const MAX_INACTIVE_COUNT_HIDDEN: number = 1
let pollingInterval: NodeJS.Timeout | null = null
const normalInterval = 1000 * 60 * 30
const isLimitTimer = true

export function startPolling(callback: () => void, interval: number = normalInterval): void {
  // 首次执行
  callback()

  pollingInterval = setInterval(() => {
    if (document.visibilityState === 'visible') {
      if (isLimitTimer) {
        activeCount++
        if (activeCount >= MAX_INACTIVE_COUNT) {
          stopPolling()
        }
      } else {
        activeCount = 0
      }
      callback() // 执行轮询任务的回调函数
    } else {
      activeCount++
      if (activeCount >= MAX_INACTIVE_COUNT_HIDDEN) {
        stopPolling()
      }
    }
  }, interval)
}

export function stopPolling(): void {
  if (pollingInterval) {
    clearInterval(pollingInterval)
    pollingInterval = null
  }
}

export function visibilityChange(callback: () => void, interval: number = normalInterval): void {
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
      activeCount = 0
      stopPolling()
      // 页面可见时重新开始轮询
      startPolling(callback, interval)
    } else {
      activeCount++
      if (activeCount >= MAX_INACTIVE_COUNT_HIDDEN) {
        stopPolling()
      }
    }
  })
}

app.vue 轮询判断是否需要更新

onMounted(() => {
  startPolling(() => {
    state.needUpgrade = checkIsUpgrade()
    console.log('needUpgrade111', JSON.stringify(state.needUpgrade))
  })
  visibilityChange(() => {
    state.needUpgrade = checkIsUpgrade()
    console.log('needUpgrade222', JSON.stringify(state.needUpgrade))
  })
})
const checkIsUpgrade = () => {
  let needUpgrade = false
  if (route.path !== '/login') {
    needUpgrade = checkUpgrade()
  }
  return needUpgrade
}

二、接口实现

接口格式

{
    code: 20000,
    msg: 'success',
    data: {
      isForceUpgrade: false,
      version: '2.1.0',
      descList: ['1. 新增xxx功能', '2. 优化xxx功能', '3. 修复xxx功能']
    }
}

请求版本信息和本地比较


/**
 * @description: 比较版本号
 * @param {string} version1
 * @param {string} version2
 * @return {*} version1>version2 返回 1;如果小于返回 -1;如果相等 返回 0
 */
export function compareVersions(version1: string, version2: string): number {
  const parts1: number[] = version1.split('.').map((part) => parseInt(part))
  const parts2: number[] = version2.split('.').map((part) => parseInt(part))

  const maxLength: number = Math.max(parts1.length, parts2.length)

  for (let i = 0; i < maxLength; i++) {
    const num1: number = parts1[i] || 0
    const num2: number = parts2[i] || 0

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
    // 如果相等,则继续比较下一个部分
  }

  return 0 // 如果版本号完全相等
}

export function requestCheckUpgrade() {
  return new Promise((resolve, reject) => {
    getCheckUpgrade()
      .then((res) => {
        if (res.code === 20000) {
          var data = JSON.parse(JSON.stringify(res.data))
          let needUpgrade = false
          const version = getVersion()
          // console.log('version', JSON.stringify(version))
          // console.log('data.version', JSON.stringify(data.version))
          // console.log('checkUpdateVersion', JSON.stringify(checkUpdateVersion))
          // console.log('needUpgrade', compareVersions(data.version, version ? version : checkUpdateVersion))
          if (compareVersions(data.version, version ? version : checkUpdateVersion) === 1) {
            needUpgrade = true
          }
          var dict = { needUpgrade: needUpgrade, upgradeData: data }
          resolve(dict)
        } else {
          reject(res.msg)
          ElMessage.warning(res.msg)
        }
      })
      .catch((err) => {
        reject(err)
      })
  })
}

app.vue 轮询调用获取版本信息的请求和弹框显示


 <UpgradeDialog v-model:is-show="needUpgrade" :upgrade-data="upgradeData" />


import { useRoute } from 'vue-router'
const route = useRoute()
import UpgradeDialog from '@/components/upgrade-dialog/index.vue'
import { checkUpgrade, startPolling, visibilityChange, requestCheckUpgrade } from '@/components/upgrade-dialog/upgradeUtils'

const state = reactive({
  needUpgrade: false,
  upgradeData: {}
})
const { needUpgrade, upgradeData } = toRefs(state)




onMounted(() => {
  startPolling(() => {
    getCheckUpgrade('startPolling')
  })
  visibilityChange(() => {
    getCheckUpgrade('visibilityChange')
  })
})
const getCheckUpgrade = (type: 'startPolling' | 'visibilityChange') => {
  // if (route.path === '/login') {
  //   return
  // }
  requestCheckUpgrade()
    .then((data: any) => {
      state.needUpgrade = data.needUpgrade
      state.upgradeData = data.upgradeData
      if (type === 'startPolling') {
        console.log('needUpgrade111', JSON.stringify(data))
      } else {
        console.log('needUpgrade222', JSON.stringify(data))
      }
    })
    .catch((err) => {
      console.log('err', JSON.stringify(err))
    })
}

注意:点击弹框确认按钮刷新页面并把最新的版本号保存到本地

这是弹框组件内的点击按钮事件

  if (props.upgradeData && props.upgradeData.version) {
    setVersion(props.upgradeData.version)
  } else {
    setVersion()
  }
  window.location.reload()

弹框组件代码

<template>
  <div class="upgrade-dialog-bg">
    <el-dialog
      v-model="isShowDialog"
      :width="dialogConfig.width"
      :append-to-body="dialogConfig.appendToBody"
      class="upgrade-dialog"
      destroy-on-close
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <template #header>
        <div class="upgrade-title">
          <div class="upgrade-title-warp">
            <span class="upgrade-title-warp-txt">{{ dialogConfig.title }}</span>
            <span class="upgrade-title-warp-version">v{{ upgradeInfo.version }}</span>
          </div>
        </div>
      </template>
      <div class="upgrade-content">
        <div v-for="(item, index) in upgradeInfo.descList" :key="index">
          <div style="margin-bottom: 10px">{{ item }}</div>
          <!-- <div :style="{ marginBottom: index === upgradeInfo.descList.length - 1 ? '0' : '10px' }">{{ item }}</div> -->
        </div>
        <div class="b-tag-warning">{{ dialogConfig.note }}</div>
      </div>
      <div class="upgrade-btn">
        <el-button v-if="!upgradeInfo.isForceUpgrade" round size="default" type="info" text @click="onCancel">{{ dialogConfig.cancelText }}</el-button>
        <el-button type="primary" round size="default" @click="onUpgrade" :loading="state.dialogSubmitBtnLoading">{{ dialogConfig.confirmText }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<!-- 
  当用户的视角离开页面的时候停止发送请求,用户回到页面视角继续请求 
  活跃状态把轮询次数清0,非活跃状态轮询次数+1,超过x次停止轮询
-->
<script setup lang="ts">
import { getVersion, setVersion } from './upgradeUtils'

const emit = defineEmits(['update:isShow'])

const props = defineProps({
  isShow: { type: Boolean, default: false },
  upgradeData: { type: Object, default: () => ({}) }
})

const { checkUpdateVersion } = __APP_INFO__

const state = reactive({
  isShowDialog: false,
  // @ts-ignore
  version: checkUpdateVersion,
  dialogSubmitBtnLoading: false,
  dialogConfig: {
    appendToBody: true,
    width: '50%',
    // title: 'New version',
    // cancelText: 'Cancel',
    // confirmText: 'Update',
    // note: 'Note: The system has been updated. Click the confirm button to refresh the page (please make sure the current page data has been saved before refreshing).'
    title: '发现新版本',
    cancelText: '残忍拒绝',
    confirmText: '马上更新',
    note: '注意:系统已更新,点击确定按钮刷新页面(请在刷新前确认当前页面数据已保存)。'
  },
  upgradeInfo: {
    isForceUpgrade: false,
    version: '1.2.0',
    descList: ['1. 新增xxx功能', '2. 优化xxx功能', '3. 修复xxx功能']
    // descList: ['1. add xxx func', '2. optimize xxx func', '3. fix xxx bug']
    // descList: [
    //   '1. 新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能',
    //   '2. 优化xxx功能优化xxx功能优化xxx功能优化xxx功能优化xxx功能优化xxx功能优化xxx功能优化xxx功能',
    //   '3. 修复xxx功能',
    //   '1. 新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能新增xxx功能',
    //   '2. 优化xxx功能',
    //   '3. 修复xxx功能',
    //   '1. 新增xxx功能',
    //   '2. 优化xxx功能',
    //   '3. 修复xxx功能',
    //   '3. 修复xxx功能',
    //   '1. 新增xxx功能'
    // ]
  }
})

const { isShowDialog, dialogConfig, upgradeInfo } = toRefs(state)

watch(
  () => props.isShow,
  (val) => {
    state.isShowDialog = val // isShow改变是同步子组件isShowDialog的值
  }
)
watch(
  () => state.isShowDialog,
  (val) => {
    emit('update:isShow', val) // isShowDialog改变时同步父组件isShow的值
  }
)
watch(
  () => props.upgradeData,
  (val) => {
    state.upgradeInfo = JSON.parse(JSON.stringify(val))
  }
)

onMounted(() => {
  // delayShow()
})

// 延迟显示,防止刷新时界面显示太快
const delayShow = () => {
  setTimeout(() => {
    state.isShowDialog = true
  }, 2000)
}

const onCancel = () => {
  state.isShowDialog = false
}
const onUpgrade = () => {
  state.dialogSubmitBtnLoading = true
  setTimeout(() => {
    if (props.upgradeData && props.upgradeData.version) {
      setVersion(props.upgradeData.version)
    } else {
      setVersion()
    }
    window.location.reload()

    // window.location.replace(window.location.href); //没有刷新缓存
    // location.reload(true); // 刷新了缓存
  }, 2000)
}
</script>

<style lang="scss">
.upgrade-dialog {
  .el-dialog__header {
    padding: 0px;
    margin-right: 0px;
    overflow: hidden;
  }
  .el-dialog__body {
    padding: 0 !important;
    max-height: calc(90vh - 111px) !important;
    overflow-y: auto;
    overflow-x: hidden;
  }
  @media screen and (min-width: 750px), (min-device-width: 750px) {
    width: max(30%, 300px);
  }
  @media screen and (max-width: 750px), (max-device-width: 750px) {
    width: max(60%, 300px);
  }
}
</style>

<style scoped lang="scss">
.upgrade-dialog {
  .upgrade-title {
    text-align: center;
    height: 130px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    &::after {
      content: '';
      position: absolute;
      // background-color: #409eff;
      background-color: var(--el-color-primary);
      width: 130%;
      height: 130px;
      border-bottom-left-radius: 100%;
      border-bottom-right-radius: 100%;
    }
    .upgrade-title-warp {
      z-index: 1;
      position: relative;
      .upgrade-title-warp-txt {
        color: white;
        font-size: 22px;
        letter-spacing: 3px;
      }
      .upgrade-title-warp-version {
        color: white;
        // background-color: #79bbff;
        background-color: var(--el-color-primary-light-3);
        font-size: 12px;
        position: absolute;
        display: flex;
        top: -2px;
        right: -50px;
        padding: 2px 4px;
        border-radius: 2px;
      }
    }
  }
  .upgrade-content {
    padding: 20px;
    line-height: 22px;
    .upgrade-content-desc {
      color: #c8c9cc;
      color: var(--el-color-info-light-5);
      font-size: 12px;
    }
  }
  .upgrade-btn {
    // border-top: 1px solid #ebeef5;
    border-top: 1px solid var(--el-border-color-lighter, #ebeef5);
    display: flex;
    justify-content: space-around;
    padding: 15px 20px;
    .el-button {
      width: 100%;
    }
  }
}

.b-tag-warning {
  display: inline-block;
  margin: 0.2rem;
  padding: 5px 10px;
  font-size: 12px;
  color: #e6a23c;
  background: #fdf6ec;
  border: 1px solid #faecd8;
  border-radius: 4px;
}
</style>


原文地址:https://blog.csdn.net/iotjin/article/details/140349880

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!