vue3 h5网页,safari浏览器使用手势右滑返回上一页,上一页不执行任何js?

问题:A页面正常跳转B页面,B页面用手势右滑屏幕返回到A页面,A页面不执行任何生命周期方法(onMounted,watch等等)如果使用浏览器底部的返回按钮,则是正常的
技术栈:vue3
环境:iphone12,iOS16
期望:需要执行一个在onMounted里面的方法,获取新数据

阅读 4.3k
2 个回答
window.addEventListener('pageshow', function(event) {
  if (event.persisted) { // 判断是否从缓存中恢复页面
    console.log('执行了pageshow');
    // 这里添加需要执行的方法
  }
});
window.addEventListener('pagehide', function(event) {
  if (event.persisted) { // 判断是否缓存当前页面
    console.log('执行了pagehide');
  }
});

或者用路由守卫

const router = createRouter({
  routes: [
    {
      path: '/A',
      name: 'A',
      component: A,
      beforeRouteUpdate(to, from, next) {
        // 这里添加需要执行的方法
        console.log('执行了beforeRouteUpdate');
        next();
      }
    },
    {
      path: '/B',
      name: 'B',
      component: B
    }
  ]
})

或者这个

// 在 A 页面中添加监听器
window.addEventListener('popstate', function(event) {
  console.log('执行了popstate');
});

Safari浏览器手势右滑返回上一页时,上一页会从缓存中加载,而不会重新执行生命周期钩子,你可以写一个 pageshow 事件监听器。

你在 A 页面中,你可以这样处理一下:

import { onMounted, onUnmounted } from 'vue';
onMounted(() => {
    window.addEventListener('pageshow', onPageShow);
});

onUnmounted(() => {
    window.removeEventListener('pageshow', onPageShow);
});
function onPageShow(event) {
      if (event.persisted) {
        // 页面是从缓存加载的,这里执行你的逻辑
   }
}
 
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题