【发布时间】: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(()=>{ console.log(this.$store.getters['courses/getCourseData']) })
标签: vue.js vuejs2 vuex store vuejs3