【问题标题】:How do you get the value of a data attribute in a component in another component without using event bus?在不使用事件总线的情况下,如何在另一个组件中获取组件中数据属性的值?
【发布时间】:2019-04-02 10:02:29
【问题描述】:

我有一个数据属性'auth',它保存用户是否登录。如果它是空的,那么用户没有登录,如果它有'loggedin',那么用户已经登录了。

这是在一个名为“App.vue”的组件中,我有另一个名为“DashboardComponent.vue”的组件。如果用户未通过身份验证,但输入“/dashboard”URL,我希望应用程序将用户踢回登录屏幕。如何将“App.vue”组件中的“auth”数据获取到“DashboardComponent.vue”并检查用户是否已通过身份验证(在仪表板呈现之前)?

编辑:

这就是我目前正在尝试的方式

[DashboardComponent]
EventBus.$on('logged-in', status => {
  this.auth = status
})

beforeMount () {
    if (this.auth !== 'loggedin') {
      router.push({name: 'login'})
    }
}

这是正确的方法吗?如果是这样,为什么它不起作用?

【问题讨论】:

标签: javascript node.js vue.js


【解决方案1】:

将数据声明到 vue 初始化的主文件中

window.App = new Vue({
  el: '#app',
  router,
  components: { App },
  data: function(){
        return {
          auth:''
        }
   }

})

之后您可以在主文件中将其更改为

mounted:function(){
  //when logged in then change status
  this.status = 'loggedIn'
}

现在使用App.status在任何组件中访问它

【讨论】:

    猜你喜欢
    • 2021-03-15
    • 2013-08-23
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    相关资源
    最近更新 更多