使用Vue3和vue-router4 4,两个不同的组件共享相同的子组件。组件模板的设置如下:
<!-- Component A -->
<template>
<ComponentA>
<Child />
</ComponentA>
</template>
<!-- Component B -->
<template>
<ComponentB>
<Child />
</ComponentB>
</template>
<!-- Child -->
<template>
<FilterResults />
</template>以下是已配置的路由:
const routes = [
{
path:'/componenta/:param',
component: ComponentA
},
{
path:'/componentb',
component: ComponentB
}
]
const router = createRouter({
history: createWebHistory(),
routes,
})在Child组件中设置了一些数据:
export default {
name: 'Child'
...,
data() {
return {
filters: {
size: [
{
selected: this.$route.query.size === "1m"
}
]
}
}
}
}上面的目标是根据路由中是否找到匹配,将selected设置为true或false。然后将结果作为支柱传递到FilterResults中:
<!-- Component A -->
<template>
<ComponentA>
<Child />
</ComponentA>
</template>
<!-- Component B -->
<template>
<ComponentB>
<Child />
</ComponentB>
</template>
<!-- Child -->
<template>
<FilterResults :filters="filters" />
</template>使用上述方法,对筛选器数据中的selected值进行评估,预期的结果是,当组件加载时,$route中的过滤器在数据中被设置为true。
问题是,ComponentA和ComponentB的子组件是相同的:
ComponentA /componenta/xyz?size=1m 不按预期工作,在路由中找到的匹配不是在filters数据中设置为true的。ComponentB /componentb?size=1m 按预期执行工作,其中在路由中找到的匹配在filters数据中被设置为true。发布于 2021-03-25 05:39:17
只有在router-view没有键的情况下,我才能重现问题,所以我假设这就是您所拥有的。
如果同一个组件有两个router-link,但具有不同的size查询参数(如下面所示),并且单击一个链接,然后单击另一个链接,Vue将重用现有组件实例,因此不会调用组件的data(),查询参数不会被重新计算。
<router-link to="/componenta/xyz?size=1m">A (size=1m)</router-link> |
<router-link to="/componenta/xyz?size=0">A (size=0)</router-link> |为了确保为每次路由更改创建一个新组件,请在router-view 钥匙 on $route.fullPath上指定一个$route.fullPath(其中包括查询参数):
<router-view :key="$route.fullPath"></router-view>发布于 2021-03-24 04:11:37
在我看来,问题就在这里,您的数据并不是重新计算路由更改,而是尝试在路由更改时修改本地数据。尝试在数据返回语句之前添加调试器,即使更改路由,它也只会出现一个。
https://stackoverflow.com/questions/66774083
复制相似问题