【问题标题】:Vuex store to return object results from firebase not workingVuex商店从firebase返回对象结果不起作用
【发布时间】:2018-06-08 15:40:40
【问题描述】:

我一生都无法弄清楚为什么这不起作用,所以希望你能提供帮助

我要做的只是通过 vuex 商店而不是在我的组件中获取请求,就像我目前作为学习 vue/nuxt 的一部分所做的那样,但只是无法使其按如下方式工作,任何人都可以看到请问我做错了什么

烦恼商店

import Vuex from "vuex";
import axios from "axios";
const URL = 'MYPATH';
const logStore = () => {
return new Vuex.Store({

state: {
  logItems: {}
},

actions: {

  setLog ({ commit }) {
    axios
      .get('URL')
      .then(r => r.data)
      .then(logItems => {
        console.log(logItems) // I am getting back my results in log here
        })
      .then(logItems => {
      commit('logItems', logItems)
    })
  }, 
},

mutations: {
  logItems (state, logItems) {
    state.logItems = logItems
  },

getters: {
    logItems(state) {
        return state.logItems // log console here is empty object
      }
},

});
};

导出默认logStore;

在我的组件中

    import { mapState } from 'vuex'

 created () {
    this.$store.dispatch('setLog', this.logItems)
    console.log(this.$store.getters.logItems) // empty object here
    },

谁能告诉我为什么我将结果返回到我的操作中,而不是返回到我的 getter 或组件中

谢谢

【问题讨论】:

    标签: vue.js axios vuex


    【解决方案1】:

    您需要在此处返回您的 logItems,以便下一个 then 可以访问它

    .then(logItems => {
        console.log(logItems) // I am getting back my results in log here
        return logItems;
    })
    

    当你不使用花括号时,函数体中的任何内容都会自动返回,就像你在这里一样

    .then(r => r.data)
    

    但是,当你确实使用花括号时,如果你需要链中的下一个函数来获取一个值,你需要返回它并在下一个函数中获取它

    .then(logItems => {
        console.log(logItems)
        return logItems
    })
    .then(thisWillBeTheReturnAbove => { // ... code ... })
    

    编辑

    正如 cmets 中提到的,我创建了一个 GitLab 存储库,其中包含一个示例,您可以在此处找到 http://gitlab.com/vitorleite/vue-firebase-todo

    您应该能够克隆它并通过执行 npm installnpm run serve 在本地运行它,您需要更改 store.js 以包含您的 Firebase 端点。我确实留下了我在评论中使用的那个,但我会在某个时候将权限更改为 read-only

    我使用@vue/cli 3.0 创建了项目,并使用示例 JsFiddle Vue Todo 代码作为基础。

    【讨论】:

      猜你喜欢
      • 2017-05-14
      • 2020-11-23
      • 2018-09-08
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 2020-06-19
      相关资源
      最近更新 更多