vite热更新导致的问题及解决

一、封装axios拦截器后,每次热更新虽然请求了一次,但是response了多次:

复制代码
import axios from "axios";
axios.interceptors.request.use()
axios.service.interceptors.response.use()

导致此问题是因为触发了多次拦截器,相当于是给axios添加了多个拦截器,所以多次触发;

解决办法:

单独对axios进行实例化,再设置拦截器

复制代码
import axios from "axios";
const service = axios.create({
  baseURL:GLOBAL_IP,
  headers: {
    'Content-Type': 'application/json', // 设置请求的Content-Type
  }
})
service.interceptors.request.use()
service.service.interceptors.response.use()

二、在移动端中使用keepalive,然后调用onActivated,里面设置定时更新的定时器,多次热更新不刷新页面的情况下会多个定时请求;

复制代码
let state = reactive({destroyTimer(){
        if(state.timer.length>0){
          for(let i=0;i<state.timer.length;i++){
            clearInterval(<number>state.timer[i])
          }
          state.timer = []
        }
      },
})
 onActivated(async () => {
      state.timer.push(setInterval(async () => {
        await state.getData();
      }, refreshTime * 1000))
      await state.getData();
    })

    onDeactivated(() => {
      state.destroyTimer()
    })
复制代码
解决办法:
   每次热更新的时候虽然不会触发onActivated,但是会触发onUnmounted,所以在unUnmounted钩子里再销毁一下就解决了热更新出现的这个问题。
复制代码
let state = reactive({destroyTimer(){
        if(state.timer.length>0){
          for(let i=0;i<state.timer.length;i++){
            clearInterval(<number>state.timer[i])
          }
          state.timer = []
        }
      },
})
 onActivated(async () => {
      state.timer.push(setInterval(async () => {
        await state.getData();
      }, refreshTime * 1000))
      await state.getData();
    })
    onUnmounted(()=>{
      state.destroyTimer()
    })

    onDeactivated(() => {
      state.destroyTimer()
    })
相关推荐
没落英雄16 小时前
简单了解 with
前端·javascript
越努力越幸运50816 小时前
webpack的学习打包工具
前端·学习·webpack
IT古董16 小时前
微前端的新纪元:Vite + Module Federation 最强指南(2025 全面技术解析)
前端
小小弯_Shelby16 小时前
vue项目源码泄露漏洞修复
前端·javascript·vue.js
兔子零102416 小时前
CSS 视口单位进化论:从 100vh 的「骗局」到 dvh 的救赎
前端·css
q***876017 小时前
项目升级Sass版本或升级Element Plus版本遇到的问题
前端·rust·sass
k***121717 小时前
【Nginx 】Nginx 部署前端 vue 项目
前端·vue.js·nginx
看晴天了17 小时前
手势操控 Three.js!效果炸裂!
前端
喝咖啡的女孩17 小时前
Promise × 定时器全场景手写
前端
h***346317 小时前
MS SQL Server 实战 排查多列之间的值是否重复
android·前端·后端