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()
    })
相关推荐
前端不太难1 小时前
《Vue 项目路由 + Layout 的最佳实践》
前端·javascript·vue.js
LYFlied1 小时前
【每日算法】 LeetCode 56. 合并区间
前端·算法·leetcode·面试·职场和发展
想学后端的前端工程师1 小时前
【Vue3组合式API实战指南:告别Options API的烦恼】
前端·javascript·vue.js
否子戈1 小时前
WebCut前端视频编辑UI框架一周开源进度
前端·音视频开发·ui kit
昔人'2 小时前
`corepack` 安装pnpm
前端·pnpm·node·corepack
萌萌哒草头将军2 小时前
pnpm + monorepo 才是 AI 协同开发的最佳方案!🚀🚀🚀
前端·react.js·ai编程
hboot3 小时前
💪别再迷茫!一份让你彻底掌控 TypeScript 类型系统的终极指南
前端·typescript
GISer_Jing3 小时前
深入拆解Taro框架多端适配原理
前端·javascript·taro
毕设源码-邱学长3 小时前
【开题答辩全过程】以 基于VUE的藏品管理系统的设计与实现为例,包含答辩的问题和答案
前端·javascript·vue.js
用户28907942162714 小时前
Spec-Kit应用指南
前端