Vuex getters未返回数据



我有一个Vuex getter,它返回courseData的状态,但由于某种原因,我无法访问它。我尝试执行console.log(this.$store.getters),但我试图访问的getter存在并且有值。但当我尝试执行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
}
},
}

由于您已经在操作中使用了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
}

最新更新