组件在 mounted() 上发出 GET 请求并响应子组件。如果我输入直接转到子组件的 URL 会发生什么?

Component makes a GET request on mounted() and props response to child component. What happens if I type URL that goes straight to child component?

所以想象一下我有这 2 URLs:

example.com/Profile
example.com/Profile/City

当访问 example.com/Profile 时,我呈现组件 Profile,当访问 example.com/Profile/City 时,我呈现组件 City

我需要发出一个 GET 请求,returns 两个组件中使用的信息。目前,我在两个组件的 mounted() 生命周期挂钩中发出 GET 请求,但我一直想知道我是否可以只在父 Profile 组件中执行一次,然后将它传递给 City,这样我就可以摆脱 1 GET 请求。

但是,我不确定如果用户直接输入 example.com/Profile/City 会发生什么?考虑到 GET 请求是在 Profile 组件的 mounted() 上执行的,我们还没有安装 Profile 因为用户直接输入了导致 City 组件的 URL , 我会在子组件中得到响应吗?

Considering the GET request is executed on mounted() of the Profile component and we haven't mounted Profile since the user straight up typed the URL that leads to City component , will I have the response in the child component?

不,你不会。您最终将没有数据。

I have been wondering if I can do it once only in the parent Profile component and then just props it down to City so that I could get rid of 1 GET request.

不是真的。但是,如果您使用像 vuex 这样的全局状态管理解决方案,您可以将请求和数据移动到这个全局状态中,并为来自两个组件的请求的请求触发 vuex 操作 mounted.

然后你可以在你的 vuex 操作中实现逻辑,如果数据已经存在(即来自之前访问过的 /profile)将跳过请求。但在那种情况下,你应该确保保存一些时间戳,这样你就不会无限期地缓存数据。

如果你希望数据经常变化,我根本不会那样缓存它,而是每次都做一个重复的请求,以确保数据尽可能新鲜。