【问题标题】:How to modify only a nested array property in store with vuex如何使用 vuex 仅修改存储中的嵌套数组属性
【发布时间】:2019-07-24 15:40:38
【问题描述】:

您好,我是 vue 和 vuex 的新手。

我在存储中发布了一些数据,需要根据用户选择修改它的嵌套数组属性。 我正在尝试在我的商店中使用“操作”,但是当我使用“this.$store.dispatch”时,我得到“未捕获的 TypeError:state.storyInfo.push 不是函数”。 如果我使用“this.$store.commit”直接提交“mutations”,我会得到未修改的原始状态。

这是我所在州的数据:

{
  "id": 1,
  "title": "Story title",
  "episodes": [
    {
      "id": 1,
      "title": "Episode 1"
    },
    {
      "id": 2,
      "title": "Episode 2"
    },
    {
      "id": 3,
      "title": "Episode 3"
    }
  ]
}

例如,如果用户选择 id = 2 的剧集,我希望状态变为:

{
  "id": 1,
  "title": "Story title",
  "episodes": [
    {
      "id": 2,
      "title": "Episode 2"
    }
  ]
}

我的 store.js 看起来像这样:

export const store = new Vuex.Store({
  state: {
    storyInfo: null
  },
  mutations: {
    setStory (state, payload) {
      state.storyInfo = payload
    },
    addInfoToStory (state, payload) {
      const data = this.state.episodes
      state.storyInfo.push(data)
    }
  },
  actions: {
    addToStory (infoToAdd, payload) {
      infoToAdd.commit('addInfoToStory', payload)
    }
  },
  getters: {
    selectedStoryInfo: state => state.storyInfo
  }
})

组件中的方法如下所示:

methods: {
  addSelectedEpisode () {
    this.$store.commit('addToStory', this.episode) // <- here if I use dispatch I get the error and no result
  },
  redirectTo () {
    this.$router.push({name: 'Read'})
  }
}

我也尝试修改网上找到的一些 TODO 示例,但我所做的似乎没有任何效果。

我做错了什么?

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    store.js,您将storeInfo 初始化为null

    push 是一种仅适用于数组的方法,因此不适用于 null 变量。

    尝试将storeInfo 设置为空数组:

    export const store = new Vuex.Store({
      state: {
        storyInfo: []
      },
    
      ...
    

    【讨论】:

    • 没有任何相关变化。如果我派遣我得到“推送不是功能”。我使用提交我得到原始数据+日志错误:未知突变类型:addToStory。
    • 我已经发布了解决方案。请注意,将 state 中的对象初始化为 null、'' 或 [] 不会有任何区别。
    【解决方案2】:

    发布我自己的解决方案。在 Store 中,将“addInfoToStory”突变替换为需要更改的故事路径:

    addInfoToStory (state, payload) {
      state.storyInfo.episodes = payload
    }
    

    这将只修改状态中的该属性。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-15
      • 1970-01-01
      • 2021-10-27
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      相关资源
      最近更新 更多