vuex动作内部状态未定义

时间:2019-03-26 01:07:15

标签: vue.js vuejs2 vuex

我从Vue-DevTools中看到播放列表状态已填充,但是当我在操作中从上下文对象中解构状态时,状态是不确定的...

以下是相关代码:

import PlaylistService from './api/PlaylistService'

export const state = {
  playlist: {},
  oldTitle: '',
  oldDescription: ''
}
export const actions = {
  async edit({ commit, state }, payload) {
    try {
      console.log(state) // **undefined?!?!**
      const updated = await PlaylistService.update(state.playlist.guid, {
        title: payload.title,
        description: payload.description
      })
      commit('edit', updated)
    } catch (error) {
      console.error(error)
    }
  }
}

export const mutations = {
  openEdit(state, payload) {
    state.playlist = payload
    state.oldTitle = payload.title
    state.oldDescription = payload.description
  },
  edit(state, payload) {
    state.playlist = payload
  },
  cancelEdit(state) {
    state.playlist.title = state.oldTitle
    state.playlist.description = state.oldDescription
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

这是来自开发工具的Vuex状态树: enter image description here

然后单击保存按钮以进行补丁请求,以上操作中的console.log(state)给出了未定义的内容。

我不知道该如何解决。任何帮助表示赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

好吧,从exportstateactions中删除mutation,因为最后已经用export default导出了它们。

const state = {
  playlist: {},
  oldTitle: '',
  oldDescription: ''
}

const actions = {
  async edit({ commit, state }, payload) {
    try {
      console.log(state) // **undefined?!?!**
      const updated = await PlaylistService.update(state.playlist.guid, {
        title: payload.title,
        description: payload.description
      })
      commit('edit', updated)
    } catch (error) {
      console.error(error)
    }
  }
}

const mutations = {
  openEdit(state, payload) {
    state.playlist = payload
    state.oldTitle = payload.title
    state.oldDescription = payload.description
  },
  edit(state, payload) {
    state.playlist = payload
  },
  cancelEdit(state) {
    state.playlist.title = state.oldTitle
    state.playlist.description = state.oldDescription
  }
}

希望这会有所帮助!