vue3全局判断页面重载

1.app.vue 通过onMounted()判断页面重载(app.vue)

import { onMounted } from 'vue';

onMounted(() => {

  console.log('调用了')

});

2.通过window.addEventListener监听页面刷新(main.js)

// 监听页面刷新事件
window.addEventListener('beforeunload', (event: BeforeUnloadEvent) => {
  // 你可以在这里做任何你需要的处理
  console.log('页面即将刷新或关闭')
  // 可选:设置返回的消息,这样用户会看到确认对话框
  event.preventDefault()
  event.returnValue = ''
})

3.使用window判断页面刷新,设置全局变量(main.js)

app.config.globalProperties.$isPageRefreshed = false;
// 检查是否是页面刷新
if (window.performance) {
  console.log(performance.navigation);
  if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
    app.config.globalProperties.$isPageRefreshed = true;
    // 调用自定义方法
  }
}

还可以设置路由监听全局变量

import {watch, getCurrentInstance} from "vue";
const { proxy } = getCurrentInstance();
// 监听当前路由
watch(
  () => router.currentRoute.value,
  (newValue: any) => {
    if(newValue.fullPath=="xxx"){
      // console.log('newValue',newValue)
      if(proxy.$isPageRefreshed) {
        console.log('isPageRefreshed', proxy.$isPageRefreshed)
         //执行方法
      }
      
    }
  },
  { immediate: true }
)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值