首页 > 解决方案 > Vuex 动作不能提交突变

问题描述

我正在为网站开发身份验证功能,我正在使用 Firebase 进行此操作。每当用户登录到 firebase 时,我在商店中的操作都会被触发并提交我的突变,因此状态会使用用户 ID 设置。不知何故,每当我尝试提交我的突变时,我都会不断收到错误:commit is not defined. 我似乎无法找到解决这个问题的方法,我上过的所有论坛都没有帮助,所以我真的希望这里有人能帮助我解决我的问题,我真的很感激。

我的行动:

  async login({ dispatch }, user) {
    const token = await auth.currentUser.getIdToken(true);
    const idTokenResult = await auth.currentUser.getIdTokenResult();

    let approved = false;
    const userData = await firestore.collection('users').doc(user.email).get();
    if (userData) {
      approved = userData.data().isApproved
    }

    const userInfo = {
      name: user.displayname || null,
      email: user.email || null,
      avatar: user.photoURL || null,
      uid: user.uid,
      approved
    };
    Cookies.set('access_token', token); // saving token in cookie for server rendering
    commit('saveUID', userInfo.uid);
  }
};

我的突变:

saveUID (state, uid) {
    state.uid = uid;
}, 

标签: vue.jsvuexnuxt.jsstore

解决方案


动作的第一个参数是context,它具有类似commit和的功能dispatch。您通过使用作为参数来提取(解构赋值) 。您可以使用来解决此问题并将提交实际分配给局部变量。dispatch{ dispatch }{ dispatch, commit }

解构赋值

async login({ dispatch, commit }, user) {
  commit('your_mutation')
}

使用上下文

async login(context, user) {
  context.commit('your_mutation')
}

推荐阅读