javascript - 如何使用 vue-router 从父路由继承 props
问题描述
我有以下路由器配置,并希望将id
路由main.parent
转换为整数,然后传递给props: true
所有子组件的子组件(给定)。
{
path: '/',
component: GrandparentComponent,
name: 'main',
children: [{
path: ':id',
component: ParentComponent,
name: 'main.parent',
props: route => {
return {
// parse URL id to int
id: parseInt(route.params.id, 10)
};
},
children: [{
path: 'details',
name: 'main.parent.child',
component: ChildComponent,
props: true,
children: [{
...
}]
}]
}]
}
但是,似乎路由函数只真正调用一次(在评估时/:id
),而不是在/:id/details
评估时。vue-router 中的相关代码似乎证实了这一点。
const route = routeToDisplay.value;
const matchedRoute = matchedRouteRef.value;
const ViewComponent = matchedRoute && matchedRoute.components[props.name];
// we need the value at the time we render because when we unmount, we
// navigated to a different location so the value is different
const currentName = props.name;
if (!ViewComponent) {
return normalizeSlot(slots.default, { Component: ViewComponent, route });
}
// props from route configuration
const routePropsOption = matchedRoute.props[props.name];
const routeProps = routePropsOption
? routePropsOption === true
? route.params
: typeof routePropsOption === 'function'
? routePropsOption(route)
: routePropsOption
: null;
...
const component = h(ViewComponent, assign({}, routeProps, attrs, {
onVnodeUnmounted,
ref: viewRef,
}));
...
我想知道是否有人试图解决同样的问题以及他们想出了什么解决方案。理想情况下,我想避免为每条子路线重复道具功能。
解决方案
Vue Router 中没有这样的功能可以通过这种方式将 props 传递给子路由。
相反,您可以使用provide
/inject
来有效地做到这一点。父母可以provide
拥有id
财产,任何后代都inject
可以:
- 在
ParentComponent.vue
中,使用toRefs()
onprops
获得ref
对id
道具的反应。 - 用于
provide()
提供id
给任何孩子(包括孩子路线)。 - 应用
key
on<router-view>
以确保基于唯一的id
. - 在
ChildComponent.vue
中,使用inject
道具注入id
来自步骤 2 的内容。
// ParentComponent.vue
<script>
/* Composition API */
import { provide, toRefs } from 'vue'
export default {
props: ['id'],
setup(props) {
const { id } = toRefs(props)
provide('id', id)
},
}
/* Options API */
import { toRefs } from 'vue'
export default {
props: ['id'],
provide() {
const { id } = toRefs(this.$props)
return { id }
},
}
</script>
<template>
<router-view :key="id" />
</template>
// ChildComponent.vue
<script>
export default {
inject: ['id'],
}
</script>
<template>
<h2>Detail {{ id }}</h2>
</template>
推荐阅读
- apache-kafka - Kafka 流可以有效地处理加入流吗?
- html - Jsoup - 隐藏的 div 类?
- javascript - 如何修复在两个特定数组中返回“未定义”的代码?
- firebase - 使用 Cloud Function 更新不同的 Collection 文档时出错
- python - Python,如何从 yandex 和 google 下载图片
- ios - 根据单击自定义 TableCellView 子项执行 segue
- arrays - 如何从两个数组中选择元素以使它们的总和最小?
- haskell - 如何部分解析产品类型
- angular - Angular 7 中仪表板的动态模板
- java - 在事件存储中找不到聚合