如何将状态设置为商店中的 api 数据

How to set state to api data in the store

我正在尝试将我的状态设置为我从 API 和商店中的 GETTER 获得的数据。

mounted() 生命周期挂钩期间触发 GETTER getProducts(),如下所示:

export const getters = {
  async getProducts() {
    axios.get('/api/products')
      .then(res => {
        var data = res.data
        commit('setProducts', data)
      })
      .catch(err => console.log(err));
  }
}

在 GETTER 中,我尝试触发一个名为 setProducts() 的 MUTATION,它看起来像这样:

export const mutations = {
  setProducts(state, data) {
    state.products = data
  }
}

但是当我 运行 我在我的控制台中收到错误 ReferenceError: commit is not defined 。 很明显,错误是触发了 MUTATION,但在互联网上连续搜索了 2 天后,我仍然找不到任何东西。

我还尝试将 commit('setProducts', data) 替换为: this.setProducts(数据) 设置产品(数据)

全部以错误结束 “类型错误:无法读取未定义的属性(读取 'setProducts')”

如果您的函数 getProduct 是在 Vue 组件中定义的,您必须像这样访问商店: this.$store.commit('setProducts', data)

如果您的函数不是在 Vue 组件中定义的,而是在外部 javascript 文件中定义的,则必须先导入您的商店

import store from './fileWhereIsYourStore.js'

store.commit('setProducts', data)

如果您的 getters export 实际上是您商店的 getter 的定义,您可以使用先导入商店的解决方案,但您应该知道在 getter 中进行提交显然不是一个好习惯.一定有更好的办法解决你的问题。

编辑:要回答您的评论,您可以这样做:

// Your store module 
export default {
  state: {
    products: []
  },

  mutations: {
    SET_PRODUCTS(state, data) {
      state.products = data
    }
  },

  actions: {
    async fetchProducts(store) {
      await axios.get('/api/products')
        .then(res => {
          var data = res.data
          store.commit('SET_PRODUCTS', data)
        })
        .catch(err => console.log(err));
    }
  }
}

现在,您可以像这样在每个组件中获取产品并填充您的商店:

// A random Vue Component
<template>
</template>

<script>
export default {
 async mounted() {
   await this.$store.dispatch('fetchProducts')

   // now you can access your products like this
   console.log(this.$store.state.products)
 }
}
</script>

我没有测试这段代码,但应该没问题。

只有操作在其上下文中有 commit,您可以 see here
吸气剂没有 commit.

否则,您也可以使用 mapActions(又名 import { mapActions } from 'vuex'),而不是 this.$store.dispatch(只是风格问题,最后没有真正的区别)。

按照 Julien 的建议重构您的代码以执行操作是一个很好的解决方案,因为这就是您使用 Vuex 的方式。

getter 通常用于具有特定结构的状态,例如按字母顺序排序等。对于公共状态访问,请使用常规状态或 mapState 助手。