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()
    })
相关推荐
悟能不能悟几秒前
VUE的国际化,怎么实现
前端·javascript·vue.js
Mr Xu_5 分钟前
解决 Vue + Axios 热更新导致响应拦截器重复注册的问题
前端·javascript·vue.js
岁岁种桃花儿16 分钟前
NodeJs从入门到上天:什么是Node.js
前端·node.js
colicode21 分钟前
语音报警接口开发参考:紧急情况下快速调用语音API发送安全警报
前端·语音识别
夏河始溢24 分钟前
一八四、Zustand 状态管理详解、与 Redux、MobX 的对比分析
前端·javascript·react.js·状态管理·zustand
Code小翊30 分钟前
TypeScript 核心语法速查
前端·javascript·typescript
家里有只小肥猫32 分钟前
uniApp下拉渐变头部 拿来即用
前端·javascript·uni-app
一起养小猫32 分钟前
Flutter for OpenHarmony 实战:科学计算器完整开发指南
android·前端·flutter·游戏·harmonyos
Jinuss33 分钟前
源码分析之React中Scheduler调度器的任务优先级
前端·react.js·前端框架
波波00741 分钟前
每日一题:在 .NET 中遍历集合(如 List<T>、数组、字典)的过程中进行增删改查会不会有影响?可能引发哪些问题?实际开发中应如何避免?
前端·list