vuejs vuex run action from action in store



我正在尝试在登录时调用fetchProfileonauthstatechanged但这些都不起作用。

this.fetchProfile()
this.store.dispatch("fetchProfile")
this.$store.dispatch("fetchProfile")

我在这一点上精神上不知所措。甚至没有运行fetchProfile中的 console.logs,也没有函数运行的证据。

actions: {
authAction({ commit }) {
firebase.auth().onAuthStateChanged(user => {
console.log("Auth Changed");
if (user) {
commit("setUser", user);
this.fetchProfile();
} else {
commit("setUser", null);
commit("setProfile", null);
}
});
},
signInAction({ commit }) {
console.log("Signing In");
firebase
.auth()
.signInWithPopup(provider)
.then(response => {
console.log("got response");
commit("setUser", response.user);
this.fetchProfile();
console.log("fetch?");
})
.catch(error => {
commit("setError", error.message);
});
},
signOutAction({ commit }) {
console.log("Signing Out");
firebase
.auth()
.signOut()
.then(() => {
commit("setUser", null);
commit("setProfile", null);
sessionStorage.clear();
})
.catch(error => {
commit("setError", error.message);
});
},
fetchProfile({ commit }) {
console.log("fetching");
firebase
.firestore()
.collection("profiles")
.doc(this.getUser.user.uid)
.get()
.then(profile => {
if (!profile.exists) {
firebase
.firestore()
.collection("profiles")
.doc(this.getUser.user.uid)
.set({
name: this.getUser.user.displayName,
creationTime: this.getUser.user.metadata.creationTime
})
.get()
.then(newProfile => {
console.log("created user");
commit("setProfile", newProfile);
console.log(this.getProfile());
});
} else if (profile.exists) {
console.log("User exists fetching profile");
commit("setProfile", profile);
console.log(this.getProfile());
}
});
}
}

您可以从第一个参数访问dispatch,例如commit

这应该有效:

authAction({ commit, dispatch }) {
firebase.auth().onAuthStateChanged(user => {
console.log("Auth Changed");
if (user) {
commit("setUser", user);
dispatch("fetchProfile");
} else {
commit("setUser", null);
commit("setProfile", null);
}
});
},

最新更新