You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将API响应的数据正确赋值给Vuex的state属性?

Vuex API数据赋值给state的正确实现

Vuex 规定所有状态修改必须通过 mutation 提交,禁止直接在 action 中操作 state,你的写法不符合规范,按照以下步骤调整即可:

  1. 首先在 Vuex 配置中新增修改 calendarOptions 的 mutation
const store = createStore({
  state: {
    calendarOptions: []
  },
  mutations: {
    // 第一个参数固定为当前state,第二个参数是传入的载荷
    SET_CALENDAR_OPTIONS(state, newOptions) {
      state.calendarOptions = newOptions
    }
  },
  // 后续是actions等配置
})
  1. 修改 action 逻辑,API请求拿到结果后通过 commit 调用上面定义的 mutation
actions: {
  // action第一个参数是context对象,解构出commit方法用于提交mutation
  async getCalendarOptions({ commit }) {
    // 此处替换为你的实际API调用逻辑
    const response = await yourApiRequest()
    // 提交mutation,将接口返回数据作为载荷传入
    commit('SET_CALENDAR_OPTIONS', response.data)
  }
}
  1. 业务需要获取数据时,在组件中触发对应的action即可
// 选项式API写法
this.$store.dispatch('getCalendarOptions')

// 组合式API写法
import { useStore } from 'vuex'
const store = useStore()
store.dispatch('getCalendarOptions')

补充说明:如果接口返回的数据结构和你需要的calendarOptions结构不匹配,可以在提交mutation之前先做数据格式化处理,再把处理后的结果传给commit的第二个参数即可。

内容的提问来源于stack exchange,提问作者Jayesh Kannan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 08:54:03