【发布时间】:2017-10-14 21:05:37
【问题描述】:
我的 VueJS 应用程序中有以下路线:
const routes = [
{
path: '/',
component: PlacesList
},
{
name: 'place',
path: '/places/:name',
component: CurrentWeather,
children: [
{
name: 'alerts',
path: 'alerts',
component: ForecastAlerts
},
{
name: 'forecast',
path: 'forecast',
component: ForecastTimeline
}
]
}
];
ForecastTimeline 接收从CurrentWeather 传递的道具:
export default {
name: 'ForecastTimeline',
props: ['forecastData'],
components: {
ForecastDay
}
}
当我从 /places/:name 导航到 /places/:name/forecast 时,一切正常。但是,当我尝试直接访问/places/:name/forecast 时,我收到Cannot read property 'summary' of undefined 错误。这是因为forecastData 是在CurrentWeather 组件中异步获取的。处理传递给嵌套路由的异步属性的正确方法是什么?
【问题讨论】:
-
您是否尝试过将 prop 定义移动到 mixin 中?这样您就可以将它作为来自同一来源的
ForcastAlerts和ForcastTimeline的一部分。我能想到的另一个选择是使用 Vuex 存储来使数据可跨组件访问。 -
我还没有尝试过mixin。 Vuex 是我计划在未来添加的东西,但我想弄清楚如何在没有它的情况下实现这一点。
-
我认为最好的其他方法是让 ForcastTimeline 组件在全局消息泵上定义一个事件,以便无论检索数据的内容如何都可以调用它
-
您可以尝试在 ForecastTimeline 组件中添加 beforeRouteEnter() 并检查异步任务是否完成,然后只能访问数据
标签: vue.js vuejs2 vue-component vue-router