控制台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
}
},
},
})
当然,这两种方案并不完美,还是得等待官方修复这个问题