I am not new to Vue. In my development environment, strict mode is enabled. I used Mutation already, but this error is always throwing out when I try to login.
(I googled a lot, but can't find a helpful answer)
I use Quasar.
https://quasar.dev/quasar-cli/vuex-store#Adding-a-Vuex-Module.
store/index.js
import Vue from "vue";
import Vuex from "vuex";
import auth from "./auth";
Vue.use(Vuex);
export default function(/* { ssrContext } */) {
const Store = new Vuex.Store({
modules: {
auth
},
// for dev mode only
strict: process.env.DEV
});
return Store;
}
Module name: auth
state.js
export default {
error: "",
token: null,
userId: null
};
actions.js
export async function login({ state, commit, dispatch }, payload) {
const { username, password } = payload;
const params = {
username,
password
};
try {
const { data, status } = await axios.post("auth/login", params);
if (status === 200) {
commit("setAuthUser", { token: data.token, userId: data.userId }); // throw error here
commit("setError", ""); // throw error here
}
} catch (error) {
console.log(error);
}
}
mutaions.js
export const setError = (state, payload) => {
state.error = payload;
};
export const setAuthUser = (state, payload) => {
state.token = payload.token;
state.userId = payload.userId;
};
Any help will be appreciated.
my Login.vue
data() {
return {
form: {
username: "admin",
password: "secret"
}
};
},
methods: {
login() {
this.$store.dispatch("auth/login", this.form);
}
}
I didn't use state directly in the markup
Read the token in the routes file to check permission.
if (to.matched.some(record => record.meta.requiresAuth)) {
if (store.state.auth.token === null) {
next({
path: "/login",
query: { redirect: to.fullPath }
});
} else {
next();
}
} else {
next();
}
});