Vuex:this.$Store.Dispatch不是一个函数

2022-03-03 00:00:00 firebase vue.js vuex

我正在尝试使用Vuex从FireBase获取数据。我正在与Firebase通信,将数据提交给突变,Getter将从州获得数据。然后我想在App.vue中显示状态数据。

在App.vue组件中,我在挂载函数中编写了调度,并尝试从Vuex获取数据。但是,我得到错误"TypeError: this.$store.dispatch is not a function",当我检查状态时,它显示为未定义。我的动作和突变写得正确吗?为什么我会收到该错误?

store.js
import Vue from 'vue';
import Vuex from 'vuex';
import firebase from 'firebase';

Vue.use(Vuex);

export default new Vuex.mapState({
    state: {
        notebooks: [],
    },
    getters: {
        getItems: (state) => {
            return state.notebooks;
        },
    },
    mutations: {
        setItems: function(state, notebooks) {
            state.notebooks = notebooks;
        },
    },
    actions: {
        async getTodos({ commit }) {
            var notebooksRef = await firebase.firestore().collection('notebooks');
            const notebookList = [];
            notebooksRef.onSnapshot((snap) => {
                snap.forEach((doc) => {
                    let notebooks = {
                        id: doc.id,
                        notebook: doc.data(),
                    };
                    notebookList.push(notebooks);
                });
                commit('setItems', notebookList);
            });
        },
    },
});

App.vue
<template>
    <div id="app"></div>
</template>

<script>
export default {
    name: 'App',
    computed: {
        notebooks: function() {         
            return this.$store.state.notebooks;
        },
    },
    mounted() {
        this.$store.dispatch('getTodos');
    },
};
</script>
main.js

import Vue from 'vue';
import App from './App.vue';
import store from './store';
import './firebase';

Vue.config.productionTip = false;

new Vue({
    store,
    render: (h) => h(App),
}).$mount('#app');

firebase.js
import firebase from 'firebase';

const config = {
    apiKey: '****',
    authDomain: '****',
    databaseURL: '****',
    projectId: '****',
    storageBucket: '****',
    messagingSenderId: '****',
    appId: '****',
};
// Initialize Firebase
firebase.initializeApp(config);



解决方案

在您的store.js文件中尝试export default new Vuex.Store({

相关文章