如何在Nuxt中监听页面重载事件并触发指定函数?
Vue项目页面重载时执行指定函数实现方案
核心实现思路是通过浏览器提供的页面加载性能API判断是否为刷新场景,无需修改自动生成的App.vue组件,即可过滤掉路由跳转场景,仅在页面重载时执行目标函数。
核心判断工具函数
// 兼容新老版本浏览器API,判断当前页面加载是否为刷新/重载场景 function isPageReload() { if (!window.performance) return false // 适配新版 PerformanceNavigationTiming API if (performance.getEntriesByType) { const navEntry = performance.getEntriesByType('navigation')[0] return navEntry?.type === 'reload' } // 兼容旧版已废弃但全浏览器支持的 performance.navigation API return performance.navigation.type === 1 }
具体实现方案
场景1:使用Vue Router的项目
在路由全局守卫中添加逻辑,新增执行标记避免重复触发:
// 路由配置文件(通常为 router/index.js) import { createRouter, createWebHistory } from 'vue-router' const router = createRouter({ history: createWebHistory(), routes: [/* 项目原有路由规则 */] }) // 全局执行标记,页面刷新后会自动重置 let reloadFnExecuted = false router.beforeEach((to, from, next) => { // 仅在页面重载且未执行过目标函数时触发 if (isPageReload() && !reloadFnExecuted) { // 替换为你需要执行的函数 yourTargetFunction() reloadFnExecuted = true } next() }) export default router
场景2:未使用Vue Router的项目
直接在项目入口文件main.js中添加判断逻辑即可:
// main.js import { createApp } from 'vue' import App from './App.vue' // 页面重载时执行目标函数 if (isPageReload()) { // 替换为你需要执行的函数 yourTargetFunction() } createApp(App).mount('#app')
注意事项
- 路由跳转属于页面内导航,不会修改页面加载性能API的返回值,因此可以100%过滤路由跳转场景
- 全局执行标记仅在页面生命周期内有效,页面刷新后会自动重置,不会影响下次重载时的函数执行
内容的提问来源于stack exchange,提问作者amani2k
相关产品推荐
相关产品推荐

