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()
    })

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值