有没有办法在vuex store中做异步函数

Is there a way to do asynchronous functions in the vuex store

我想从我的数据库中获取我的产品并将其直接放入我的状态(store vuex) 我从异步函数中获取我的产品

    async list(options = ''){
        const res = await fetch(this.url+options, {
            method: 'GET'
            // headers: this.headers,
        })
        const data = await res.json()
        return data
    }
    

我的问题是在我的商店中我无法使用异步功能

const state = {
    products: getProduct().then((res)=>{return res}),
    consumption: []
}

我得到了一个 Promesse,我想要得到我的对象数组

修改你的 vuex 存储并添加一个操作,它将为你获取数据,然后调用 mutaion 来更新你的状态:

export default {
  state: {
    products: [],
    consumption: []
  },
  mutations: {
    SET_PRODUCTS(state, products) {
      state.products = products;
    }
  },
  actions: {
    async fetchProducts({ commit }, { url, options, headers }) {
      const res = await fetch(url + options, {
            method: 'GET'
            headers,
      });
      const data = await res.json();
      commit('SET_PRODUCTS', data);
    },
  }
}

然后在需要时(在您的组件的初始阶段?)您只需启动操作:

this.$store.dispatch('fetchProducts');