[英]How do you get the value of a data attribute in a component in another component without using event bus?
I have a data attribute 'auth', which holds whether the user is logged in or not. 我有一个数据属性“ auth”,该属性保存用户是否已登录。 If it is empty then the user is not logged in, if it has 'loggedin' in it then the user is logged in.
如果为空,则用户未登录;如果其中具有“ loggedin”,则用户已登录。
This is in one component called 'App.vue' and i have another component called 'DashboardComponent.vue'. 这在一个名为“ App.vue”的组件中,而我在另一个名为“ DashboardComponent.vue”的组件中。 If the user isn't authenticated, but types in '/dashboard' URL, i want the app to kick the user back to the login screen.
如果用户未通过身份验证,但输入了“ / dashboard” URL,我希望该应用程序将用户踢回登录屏幕。 How do i get the 'auth' data from the 'App.vue' component into the 'DashboardComponent.vue' and check if the user is authenticated (before the dashboard renders)?
如何从“ App.vue”组件获取“ auth”数据到“ DashboardComponent.vue”并检查用户是否已通过身份验证(在仪表板呈现之前)?
EDIT: 编辑:
This is how im currently trying to do it 我目前正在尝试这样做
[DashboardComponent]
EventBus.$on('logged-in', status => {
this.auth = status
})
beforeMount () {
if (this.auth !== 'loggedin') {
router.push({name: 'login'})
}
}
Is this the correct method? 这是正确的方法吗? If so, why is it not working?
如果是这样,为什么它不起作用?
Declare your data into main file where vue initializes like 将数据声明到主文件中,其中vue会像这样初始化
window.App = new Vue({
el: '#app',
router,
components: { App },
data: function(){
return {
auth:''
}
}
})
after that you may change it in main file as 之后,您可以在主文件中将其更改为
mounted:function(){
//when logged in then change status
this.status = 'loggedIn'
}
Now access it in any component using App.status
现在使用
App.status
在任何组件中访问它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.