尝试访问Vue组件中mount()中的状态对象

时间:2019-02-17 01:21:42

标签: vue.js vuejs2 vuex

我有一个持有用户ID的Vuex状态。在我组件的mounted()中,我尝试使用该用户ID,但始终为null

如何将状态从计算出的mapGetters转移到mounted()中?

这是我的computed

computed: {
  ...mapGetters('auth', [
    'userid'
  ])
}

这是我的mounted()

mounted () {
  HTTP.get('account/' + this.userid + '/')
      .then((response) => {
        this.account = response.data
      })
}

this.userid始终为null

顺便说一句,当我查看Vue检查器时,auth/userid在getter auth/userid中具有正确的值。如何从auth.userid访问mounted()

2 个答案:

答案 0 :(得分:0)

调试

要调试此功能,请先跳过mapGetters,甚至跳过getters,然后直接返回状态。

例如。

computed:{
   userId() { return this.$store.state.auth.userid }
}

我不知道您的商店或模块的设置方式,因此您可能需要稍作更改。

一旦可行,将其添加到您的吸气剂中,并使用this.$store.getters.userid等。

最后,在可行时,请尝试使用原始的mapGetters并仔细检查模块别名。

可能的异步问题

另一方面,现在,如果您的getter是async,则在用户ID承诺解析之前,您还将获得null。您将必须使用asyncComputed,或等待装入结果。

答案 1 :(得分:0)

userid在安装组件时可能不可用。您可以通过观察userid的值来修复它,并且仅在userid更改并可用时才调用HTTP请求:

computed: {
  ...mapGetters('auth', [
    'userid'
  ])
},
watch: {
  'userid': {
    handler (newVal) {
      if (newVal) { // check if userid is available
        this.getAccountInformation()
      }
    },
    immediate: true // make this watch function is called when component created
  }
},
methods: {
  getAccountInformation () {
    HTTP.get('account/' + this.userid + '/')
        .then((response) => {
          this.account = response.data
        })
  }
}
相关问题