Currently, I am utilizing vuex with index.js and auth.js stored in the store folder. My goal is to perform a basic sign-in operation within my signin.vue by calling an action from the store. However, I encountered the error 'Uncaught (in promise) ReferenceError: dispatch is not defined' when attempting to call an action from another action using the dispatch key in auth.js.
index.js
import Vue from 'vue'
import Vuex from 'vuex'
import auth from './auth'
Vue.use(Vuex);
export default new Vuex.Store({
state: {},
mutations: {},
actions: {},
modules: {
auth
}
})
auth.js
import axios from "axios";
export default {
namespaced: true,
state: {
token: null,
user: null
},
mutations: {
SET_TOKEN(state, token) {
state.token = token;
},
SET_USER(state, data) {
state.user = data;
}
},
actions: {
async signIn(_, credentials) {
let response = await axios.post("auth/signin", credentials)
/* eslint-disable */
dispatch('attempt', response.data.token);
},
async attempt({commit}, token) {
commit("SET_TOKEN", token);
try {
let response = await axios.get('auth/me', {
headers: {
'Authorization': 'Bearer ' + token
}
});
commit("SET_USER", response.data)
} catch (e) {
commit("SET_TOKEN", null);
commit("SET_USER", null);
}
}
}
}
SignIn.vue
<template>
<div>
<form @submit.prevent="submit">
<div>
<label for="email">Email</label>
<input id="email" type="email" name="email" v-model="form.email">
</div>
<div>
<label for="password">Password</label>
<input id="password" type="password" name="password" v-model="form.password">
</div>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>
</template>
<script>
import {mapActions} from "vuex";
export default {
name: "signIn",
data() {
return {
form: {
email: "",
password: ""
}
}
},
methods: {
...mapActions({
signIn: 'auth/signIn'
}),
submit() {
this.signIn(this.form)
}
}
}
</script>