关于解决nuxt3快速切换页面时导致白屏数据丢失的BUG

控制台BUG内容:

Uncaught DOMException: Failed to execute 'insertBefore' on 'Node': The node before which the new node is to be inserted is not a child of this node.

关于此问题的一个官方的issue:https://github.com/vuejs/core/issues/8105
发生场景:
当我们快速切换页面的时候,页面就有可能触发这个bug,导致整个页面白屏!
这是一个远古bug,在3.0预览版的时候就存在,都Nuxt3.6稳定版了,还没修复,以下是目前解决这个问题的两个方案
方案1:既然是白屏,那么就能使用刷新来解决,最暴力的方法就是直接使用刷新,但代价就是你可能会丢失一些存在于缓存中的数据,如vuex/pinia,路由历史等:

if (process.client) {
  window.onerror = function (e: any) {
    if (e.includes("NotFoundError:")) {
      document.location.reload()
      return true;
    }

  }
}

方案2:
重写router钩子函数,我们在plugins这个目录下创建一个文件,名字随便你,然后将以下代码复制进去,这种方法不会让你丢失之前跳转过的路径,以便用户可以使用游览器的回退

export default defineNuxtPlugin({
    name: 'router',
    hooks: {
        'page:start': function () {
            const nuxtApp = useNuxtApp()
            nuxtApp.$router.running = false
            nuxtApp.$router.beforeEach((to, from, next) => {
                if (nuxtApp.$router.running) { next(true) }
                else {
                    nuxtApp.$router.nextRoute = to.fullPath
                    next(false)
                }
            })
        },
        'page:transition:finish': function () {
            const nuxtApp = useNuxtApp()
            nuxtApp.$router.running = true
            if (nuxtApp.$router.nextRoute) {
                nuxtApp.$router.push(nuxtApp.$router.nextRoute)
                console.log(nuxtApp.$router.nextRoute)
                nuxtApp.$router.nextRoute = null
            }
        },
    },
})

当然,这两种方案并不完美,还是得等待官方修复这个问题

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值