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()
    })
相关推荐
运维阿江5 分钟前
【小白学HTML5】盒模型_第一讲
前端·html·html5
码界领航17 分钟前
【2025最新版】Chrome谷歌浏览器如何能恢复到之前的旧版本
前端·chrome
乐多_L1 小时前
使用vue3框架vue-next-admin导出表格excel(带图片)
前端·javascript·vue.js
南望无一1 小时前
React Native 0.70.x如何从本地安卓源码(ReactAndroid)构建
前端·react native
Mike_188702783511 小时前
1688代采下单API接口使用指南:实现商品采集与自动化下单
前端·python·自动化
鲨鱼辣椒️面1 小时前
HTML视口动画
前端·html
一小路一1 小时前
Go Web 开发基础:从入门到实战
服务器·前端·后端·面试·golang
堇舟1 小时前
HTML第一节
前端·html
纯粹要努力2 小时前
前端跨域问题及解决方案
前端·javascript·面试
小刘不知道叫啥2 小时前
React源码揭秘 | 启动入口
前端·react.js·前端框架