Skip to content

Instantly share code, notes, and snippets.

@thatside
Created December 18, 2017 10:08
Show Gist options
  • Save thatside/105681ea1fb8929a8eb5b4ce2a675896 to your computer and use it in GitHub Desktop.
Save thatside/105681ea1fb8929a8eb5b4ce2a675896 to your computer and use it in GitHub Desktop.
import Vue from 'vue';
import Vuex from 'vuex';
import * as actions from './actions';
import * as getters from './getters';
import user from './modules/user/user';
Vue.use(Vuex);
const debug = process.env.NODE_ENV !== 'production';
export default new Vuex.Store({
actions,
getters,
modules: {
user,
},
strict: debug,
});
....
created: () => console.log(mapState('user', ['username'])), //for debug
computed: {
...mapState('user', ['username'])
},
....
import * as mutationTypes from './mutation_types';
import * as actionTypes from './action_types';
const state = {
username: '',
pending: false,
};
const getters = {
isLoggedIn: () => !(localStorage.getItem('token') === null),
};
const actions = {
[actionTypes.LOGIN]({ commit }, credentials) {
commit(mutationTypes.LOGIN_START); // show spinner
return new Promise((resolve) => {
setTimeout(() => {
const result = true;
if (result) {
/* eslint no-console: [0] */
const credentialsString = ' '.concat(...credentials);
console.log(`Logging with credentials ${credentialsString}`);
localStorage.setItem('token', 'JWT');
commit(mutationTypes.LOGIN_SUCCESS, credentials);
resolve();
} else {
commit(mutationTypes.LOGIN_FAILED, credentials);
resolve();
}
}, 1000);
});
},
[actionTypes.LOGOUT]({ commit }) {
localStorage.removeItem('token');
commit(mutationTypes.LOGOUT);
},
};
/* eslint no-shadow: ["error", { "allow": ["state"] }] */
const mutations = {
[mutationTypes.LOGIN_START](state) {
state.pending = true;
},
[mutationTypes.LOGIN_SUCCESS](state, credentials) {
state.pending = false;
state.username = credentials.username;
},
[mutationTypes.LOGIN_FAILED](state) {
state.pending = false;
},
[mutationTypes.LOGOUT](state) {
state.isLoggedIn = false;
},
};
export default {
namespaced: true,
state,
getters,
actions,
mutations,
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment