我正在我的 SPA (vue) 中设置导航,它使用 beforeRouteEnter
Hook 调用后端并检查用户是否经过身份验证。
从登录页面导航到 protected 页面时,这会重定向到相同的登录页面(如果未经过身份验证)。为了向用户解释他们首先需要进行身份验证,我想显示一条消息。
使用props
,将数据传递到登录页面是可行的。但是,如果此重定向来自/login ==>/protectedRoute ==>/login 则不会进行任何更改,因为 vue 重用了此组件。在大多数情况下,这种行为是需要的,但在这种特殊情况下却不是。
beforeRouteEnter
看起来像这样。
beforeRouteEnter (to, from, next) {
return axios.post('/api/auth')
$.then(result => {
next()
})
.catch(err => {
next({name:"Login", params:{auth: "false"}});
})
}
如果我从 '/guestRoute'
移动到 '/protectedRoute'
,一切正常,数据会在 '/login'
中传递> 重定向后的组件。
谢谢
最佳答案
通常,这可以通过使用状态管理来完成,例如 vuex对于 vue. 您可以调用分配应用程序级别错误,它们将可供您的所有组件使用。
Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
这意味着您的应用程序数据将由一家商店管理。 您的应用程序可以有一个像这样的商店
export default new Vuex.Store({
state: {
status: '',
token: localStorage.getItem('token') || '',
user : {},
error: ''
},
mutations: {
},
actions: {
},
getters : {
}
})
因此,您可以检查将任何错误分配给存储中的错误属性,并在组件内添加检查是否存在错误。
关于javascript - 如何将数据传递给正在重用的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58672319/