【问题标题】:Vuex getters not returning the dataVuex getter 不返回数据
【发布时间】:2021-09-30 06:35:21
【问题描述】:

我有一个返回 courseData 状态的 Vuex getter,但由于某种原因,我无法访问它。我试图做console.log(this.$store.getters) 并且我试图访问的吸气剂存在并且具有价值。但是当我尝试执行console.log(this.$store.getters.getCourseData)console.log(this.$store.getters['courses/getCourseData']) 时,它会返回一个空数组而不是一个对象。

组件:

<script>
import { mapActions, mapGetters } from 'vuex'

export default {
  data() {
    return {
      data: null,
    }
  },
  methods: {
    ...mapActions('courses', ['fetchCourseData']),
  },
  computed: {
    ...mapGetters('courses', ['getCourseData'])
  },
  created() {
    this.fetchCourseData(this.$route.params.code) // <-- This line sets the state
    console.log(this.$store.getters) // <-- List of store getters
    console.log(this.$store.getters['courses/getCourseData']) // <-- Returns empty array
    console.log(this.$store.getters.getCourseData) // <-- Returns undefined
  }
}
</script>

商店:

import axios from 'axios'

export default {
  namespaced: true,
  state: {
    courseData: [],
  },
  getters: {
    getCourseData(state) {
      return state.courseData
    }
  },
  actions: {
    async fetchCourseData({ commit }, code) {
      await axios
        .get('teacher/course-management/course/code/' + code)
        .then(response => {
          commit('SET_COURSE_DATA', response.data.data)
        })
    }
  },
  mutations: {
    SET_COURSE_DATA(state, courseData) {
      state.courseData = courseData
    }
  },
}

【问题讨论】:

  • courseData 是异步分配的。您尝试立即访问它。 getters.getCourseData 是一个错误,因为它是命名空间
  • 我尝试同步进行只是为了测试它,但问题仍然存在。我尝试在检索 getter 时添加 setTimeOut() 方法,它仍然是一样的。
  • 你测试的方式不对。您需要等待操作。带着承诺。如果状态更新失败,显然它不会成功。
  • 试试this.fetchCourseData(this.$route.params.code).then(()=&gt;{ console.log(this.$store.getters['courses/getCourseData']) })

标签: vue.js vuejs2 vuex store vuejs3


【解决方案1】:

既然您已经在您的操作中使用了async/await,那么您也可以在您的created 方法中使用它。

async created() {
    await this.fetchCourseData(this.$route.params.code) // <-- This line sets the state
    console.log(this.$store.getters) // <-- List of store getters
    console.log(this.$store.getters['courses/getCourseData']) // <-- Returns empty array
    console.log(this.$store.getters.getCourseData) // <-- Returns undefined
  }

【讨论】:

    猜你喜欢
    • 2021-05-04
    • 2018-11-16
    • 2020-01-26
    • 2019-10-09
    • 2019-07-31
    • 1970-01-01
    • 2021-08-23
    • 2021-12-11
    • 2017-12-03
    相关资源
    最近更新 更多