无法读取Vuex中未定义的属性“ dispatch”

Tom*_*paz 7 vue.js vuex

我正在尝试在vuex存储中的'logOutUser'上执行调度,并且在respone中收到以下错误消息:

TypeError:无法读取未定义的属性“ dispatch”

deleteUser.vue(无法从中执行分派操作的组件):

<template>
    <v-dialog v-model="openDelete" persistent max-width="500px">
        <v-card>
            <v-card-title>
                <h4>Delete User</h4>
            </v-card-title> 
            <v-card-text>
                <h2>Are You Sure?</h2>
                <p>Deleting your user is a permanent action.</p>
                <br>
                <br>
                <v-btn
                 color="primary"
                 @click="deleteUser">
                 Delete User
                </v-btn>
                <v-btn
                 color="primary"
                 @click="openDelete = false">
                 Close
                </v-btn>  
            </v-card-text>  
        </v-card>   
    </v-dialog> 
</template>
<script>
import router from '../../router/index.js'
const firebase = require('../../firebaseConfig.js')
export default {
    data: function(){
        return {
            openDelete: true
        }
    },
    methods: {
        deleteUser: function(){
            let user = firebase.auth.currentUser
            const docId = user.uid
            console.log("Trying to delete user ", docId)
            user.delete().then(function() {
            }).catch(function(error) {
                console.error("Error deleting user: ", error)
            });
            firebase.firestore.collection("users").doc(docId).delete().then(() => {
                        console.log('Trying to Log Out in Vuex')
                        this.$store.dispatch('user/logOutUser')
                        alert("User Deleted Successfully!")
                }).catch(function(error) {
                    console.error("Error removing document: ", error);
                });
            router.push('hello')    
            this.openDelete = false
        }
    }
}
</script>
Run Code Online (Sandbox Code Playgroud)

store.js:

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import genre from './modules/genre'

Vue.use(Vuex)

export default new Vuex.Store({
    modules: {
        user,
        genre
    }
})
Run Code Online (Sandbox Code Playgroud)

user.js:

const firebase=require('../firebaseConfig.js')

const state = {
    currentUser: null,
    userProfile: {}
}

const actions = {
        fetchUserProfile({commit, state}, uid){
            firebase.firestore.collection("users").doc(uid).get().then((doc)=>{
                commit('setUserProfile', doc.data())
            }).catch((error)=>{
                console.error(error)
            })
        },
        logOutUser({commit, state}){
            commit('setCurrentUser', null)
            commit('setUserProfile', {})
            console.log('Logged Out In Vuex')
        }
}

const mutations = 
    {
        setCurrentUser(state, val){
            state.currentUser = val
        },
        setUserProfile(state, val){
            state.userProfile = val
        }
    }

export default {
    namespaced: true,
    state,
    actions,
    mutations
}   
Run Code Online (Sandbox Code Playgroud)

编辑:这是我的main.js文件:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store.js'
const firebase = require('./firebaseConfig.js')

Vue.config.productionTip = false

let app

firebase.auth.onAuthStateChanged(user => {
  if(!app){
    /* eslint-disable no-new */
    app = new Vue({
      el: '#app',
      router,
      store,
      components: { App },
      template: '<App/>'
    })
  }
});
Run Code Online (Sandbox Code Playgroud)

我应该提到的是,我正在从应用程序中的另一个组件分派此操作,并且从那里开始它的运行情况非常好。

谢谢!

Kon*_*mba 14

那是因为您可能没有store向Vue的根实例添加选项。通过提供它,您将能够从root的所有子组件访问存储。因此,您的根实例应如下所示:

import store from './store'

const app = new Vue({
  /* .. other properties .. */
  store
})
Run Code Online (Sandbox Code Playgroud)

现在,您可以this.$store在组件内自由使用。

  • 你好!事实上我正在这样做。它在我的 main.js 文件中,我会将其添加到原始问题中。 (2认同)

小智 7

目前还不清楚为什么没有定义它,以及为什么它在使用模块时工作,而不是在没有模块的情况下工作。它可能与构建过程/转译器有关。如果use实际上是Vue类的静态方法,则将$store通过通过安装插件在所有实例之间共享use,但事实并非如此。看起来Vue应该是 Vue 模块导出的一个类,但它的行为似乎像一个实例。

我发现有效的是以下之一(首选#3):

1.Vue.use使用Vuex的地方调用

src
??? App.vue
??? main.js <- Vue.use(Vuex)
??? router 
?   ??? index.js <- Vue.use(Vuex)
??? store
    ??? myModule.js
    ??? index.js <- Vue.use(Vuex)
Run Code Online (Sandbox Code Playgroud)
// store/index.js
import Vue from "vue"; // This module's Vue is not the same instance as that referenced in main.js
import Vuex from "vuex";
import myModule from "./myModule.js";

// Required before creating new store instance
Vue.use(Vuex);

export const store = new Vuex.Store(myModule);
Run Code Online (Sandbox Code Playgroud)
// main.js
import Vue from "vue"; // this module's Vue is different from store/index.js' Vue
import Vuex from "vuex";
import app from "./App";
import router from "./router/index.js";
import { store } from "./store/index.js";

// this part is essential despite already calling Vue.use in store/index.js
Vue.use(Vuex);
// Or, see alternative below

new Vue({
    ...,
    router,
    store,
    components: { app }
});
Run Code Online (Sandbox Code Playgroud)

2.$store为所有实例设置Vue

(正如 yukashima huksay 所指出的)

// store/index.js
import Vue from "vue"; // This module's Vue is not the same instance as that referenced in main.js
import Vuex from "vuex";
import myModule from "./myModule.js";

// Required before creating new store instance
Vue.use(Vuex);

export const store = new Vuex.Store(myModule);
Run Code Online (Sandbox Code Playgroud)
Vue.prototype.$store = store;
Run Code Online (Sandbox Code Playgroud)

3. 将全局Vue实例导入 store 和 main

// main.js
import Vue from "vue"; // this module's Vue is different from store/index.js' Vue
import Vuex from "vuex";
import app from "./App";
import router from "./router/index.js";
import { store } from "./store/index.js";

// this part is essential despite already calling Vue.use in store/index.js
Vue.use(Vuex);
// Or, see alternative below

new Vue({
    ...,
    router,
    store,
    components: { app }
});
Run Code Online (Sandbox Code Playgroud)
// global.js
import vue from "vue";
export const Vue = vue;

// or if you're not using babel, you can use real javascript…,
export { Vue } from "vue";
Run Code Online (Sandbox Code Playgroud)
// store/index.js
import { Vue } from "../global.js";
import vuex from "vuex";
import myModule from "./myModule.js";

Vue.use(vuex);

export const store = new vuex.Store(myModule);
Run Code Online (Sandbox Code Playgroud)
// main.js
import { Vue } from "./global.js";
import store from "./store/index.js";
import router from "./router/index.js";
import app from "./App";

new Vue({
    ...,
    router,
    store,
    components: { app }
});
Run Code Online (Sandbox Code Playgroud)