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()
    })
相关推荐
wkj0013 小时前
vue中 js-cookie 用法
前端·javascript·vue.js
GoldKey7 小时前
gcc 源码阅读---语法树
linux·前端·windows
Xf3n1an8 小时前
html语法
前端·html
张拭心8 小时前
亚马逊 AI IDE Kiro “狙击”Cursor?实测心得
前端·ai编程
烛阴8 小时前
为什么你的Python项目总是混乱?层级包构建全解析
前端·python
@大迁世界9 小时前
React 及其生态新闻 — 2025年6月
前端·javascript·react.js·前端框架·ecmascript
红尘散仙9 小时前
Rust 终端 UI 开发新玩法:用 Ratatui Kit 轻松打造高颜值 CLI
前端·后端·rust
新酱爱学习9 小时前
前端海报生成的几种方式:从 Canvas 到 Skyline
前端·javascript·微信小程序
袁煦丞10 小时前
把纸堆变数据流!Paperless-ngx让文件管理像打游戏一样爽:cpolar内网穿透实验室第539个成功挑战
前端·程序员·远程工作
慧慧吖@10 小时前
关于两种网络攻击方式XSS和CSRF
前端·xss·csrf