在我的 Vue 项目中,我使用的是 vue-router。当我从某个页面导航“离开”时,我收到一个模糊的错误,并且路由器停止工作。单击链接会更新浏览器中的 URL,但应用程序不会导航到相应的页面。 错误是
类型错误:无法读取 null 的属性(读取“parentNode”)
当用户更改过滤和排序选项时,相关页面使用观察程序来更新路线
query
参数。这样,当页面刷新/复制/添加书签时,返回时将选择相同的选项。
watch(
() => route.query,
() => {
selectedAddresses.value = selectedAddressesQuery.value
selectedStatuses.value = selectedStatusesQuery.value
selectedSortOrder.value = selectedSortOrderQuery.value
},
{ deep: true }
)
watch(
() => [
selectedAddresses.value,
selectedStatuses.value,
selectedSortOrder.value,
],
async () => {
router.replace({
query: {
...route.query,
address: selectedAddresses.value,
sort: selectedSortORder.value,
status: selectedStatuses.value,
},
})
}
)
为什么当我离开该页面时会收到此错误?
解决方案是向监视处理程序添加一条保护语句,以检查我们是否仍在当前页面上。
watch(
() => route.query,
() => {
// prevent triggering on page leave, which clears the query
if (route.name !== 'invoices') return
selectedAddresses.value = selectedAddressesQuery.value
selectedStatuses.value = selectedStatusesQuery.value
selectedSortOrder.value = selectedSortOrderQuery.value
},
{ deep: true }
)
这可以防止第二个观察者(观察正在设置的值)被触发,该观察者试图更新不再存在的路线。
<Suspense>
,其中
#default
或#fallback
的插槽提供了包含多个根元素或仅包含文本的源。
尽管 Vue3 允许多个根元素,但用于路由视图的组件仍然应该只有一个根元素如果出现在
#default
或
#fallback
插槽中,以下内容将导致此类错误:
/** BAD: A lone string **/
<template #fallback>
Loading...
</template>
/** GOOD: Wrapped in a single DIV **/
<template #fallback>
<div>Loading...</div>
</template>
/** BAD: More than one root element in a routed component **/
<template>
<component :is="Compnent">
<div>Line 1</div>
<div>Line 2</div>
</component>
</template>
/** GOOD: Single root element **/
<template>
<component :is="Compnent">
<div>
<div>Line 1</div>
<div>Line 2</div>
</div>
</component>
</template>
<Teleport>
。
当具有v-if
的页面尝试渲染时,目标(“to”)节点不存在(因为
<Teleport>
)。所以,你可以尝试注释掉<Teleport>
,看看是否有帮助
aStore.getter
返回true
<template>
<ComponentA v-if="aStore.getter" />
<ComponentB v-else />
</template>
ComponentA 的内部脚本设置
<script lang="ts" setup>
const aStore = useStore()
await aStore.runAction() // afterwards, aStore.getter returns false
</script>