【问题标题】:Vuex stores state is undefined in console, but Vue tool is showing that are working properlyVuex 存储状态在控制台中未定义,但 Vue 工具显示工作正常
【发布时间】:2020-04-30 18:51:57
【问题描述】:

我想在 web 中显示我的 getter,但在 console.log 中我有未定义的错误。但在 vue 开发工具中,我的 getter 正在工作。

我的组件代码:

export default {
data: () => ({
  items: [
    { text: 'Real-Time', icon: 'mdi-clock' },
    { text: 'Audience', icon: 'mdi-account' },
    { text: 'Conversions', icon: 'mdi-flag' },
  ],
}),
computed: {
  Question(){
    return this.$store.getters.getQuest
  }
},
methods: {
  Next(){
    this.$store.commit('incrementIndex')
  }
},

}

这是我的 vuex :

 export default new Vuex.Store({
  state: {
    question: [],
    index: 0
  },
  getters: {
    getQuest: state => {
      let a = state.question[state.index]
      let answer = [...a.incorrect_answers, a.correct_answer]
      return {
        question: a,
        answer: answer
      }
    }

  },

【问题讨论】:

  • 你能添加你得到的错误
  • @Vincent,请尝试提供足够的信息,以便其他人正确理解您的问题。
  • @Himanshu 我只是上传错误图片
  • 在盲目访问它的索引之前检查你的getter中state.question的长度。如果为空,返回一个合适的默认值
  • @Vincent 您能否将 getter 中的 question 数组的值打印到控制台,看看它是否定义了不正确的答案?如果这是问题,只需检查您的吸气剂。

标签: vue.js vue-cli


【解决方案1】:

在 getter 中,您需要检查是否所有信息都已加载。所以这大致就是我要做的:

 export default new Vuex.Store({
  state: {
    question: [],
    index: 0
  },
  getters: {
    getQuest: state => {
      let a = state.question[state.index]
      if (a){
       let answer = [...a.incorrect_answers, a.correct_answer]
       return {
        question: a,
        answer: answer
       }
      } else {
       return null
    }

  },

【讨论】:

  • 哇,它的工作很好,谢谢,但你能告诉我,这样的案例叫什么名字,我可以在 youtube 上研究它
  • 哇,它的工作很好,谢谢,但你能告诉我,这样的案例叫什么名字,我可以在 youtube 上研究它
  • 我不知道。在某些时候,您必须超越 youtube。好像就是这个了。
【解决方案2】:

您收到未定义的错误,因为最初 question 是一个空数组。 所以 state.question[state.index] 基本上是 undefined 然后您尝试访问 undefined 的属性 incorrect_answers ,这将不起作用并且会给出 undefined 错误

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 2021-11-22
    • 1970-01-01
    • 2019-03-21
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-09-09
    相关资源
    最近更新 更多