Vuex 存储从 firebase 返回对象结果不起作用



我一辈子都想不通为什么这不起作用,所以希望你能提供帮助

我所做的只是通过 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
}
},
});
};

导出默认日志库;

在我的组件中,我有

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

谁能告诉我为什么我把结果恢复到我的操作中,而不是回到我的吸气剂或组件中

谢谢

您需要在此处返回您的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 ... })

编辑

如评论中所述,我创建了一个 GitLab 存储库,其中包含一个示例,您可以在 http://gitlab.com/vitorleite/vue-firebase-todo 中找到该示例。

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

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

最新更新