vuex操作无法访问属性值

nfeuvbwi  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(312)

我似乎无法将数据传递到vuex操作。我总是收到错误信息 TypeError: can't access property x, data is undefined . 我已经做了一些不同的方法来传递属性值,但我不能让它工作。你能看看我的代码吗,我做错了什么?
商店:

import axios from 'axios'

export default {
  namespaced: true,
  state: {
    announcements: []
  },
  getters: {},
  actions: {
    createAnnouncement({ commit }, courseId, data) {
      return new Promise((resolve, reject) => {
        axios
        .post(`teacher/courses/announcements/create/${courseId}`, { title: data.title, message: data.message })
        .then((response) => {
          commit('ADD_ANNOUNCEMENT', response.data.data)
          resolve(response)
        })
        .catch((error) => { reject(error) })
      })
    }
  },
  mutations: {
    ADD_ANNOUNCEMENT(state, newAnnouncement) {
      state.announcements.push(newAnnouncement)
    }
  }
}

组成部分:

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

export default {
  data() {
    return {
      title: '',
      message: '',
    }
  },
  computed: {
    ...mapGetters('courses', ['getCourseData'])
  },
  methods: {
    ...mapActions('announcements', ['createAnnouncement']),
    onSubmit() {
      const { announcementTitle, announcementMessage } = this
      const courseId = this.getCourseData.id
      this.createAnnouncement(courseId, { title: announcementTitle, message: announcementMessage }) 
    }
  }
}
</script>
8mmmxcuj

8mmmxcuj1#

操作只接受两个参数:上下文和可选负载。
尝试将您的操作更改为

createAnnouncement({ commit }, { courseId, data }) {
  //...
}

并将其与

const payload = {
  courseId: this.getCourseData.id,
  data: {
    title: this.announcementTitle,
    message: this.announcementMessage
  }
}
this.createAnnouncement(payload)

看见https://vuex.vuejs.org/api/#actions

相关问题