Skip to content

Instantly share code, notes, and snippets.

@warlock
Last active December 4, 2024 07:39
Show Gist options
  • Save warlock/110d2965e4a3ccfd5d92e9ecfc808039 to your computer and use it in GitHub Desktop.
Save warlock/110d2965e4a3ccfd5d92e9ecfc808039 to your computer and use it in GitHub Desktop.
Vuex and Vue.js Session Control Example
<template>
<div id="login">
<div v-if="getToken === ''">
<input type="text" v-model="user">
<br>
<input type="password" v-model="password">
<br>
<button @click="handleLogin">LOGIN</button>
</div>
<div v-else>
{{getUserId}} with token: {{getToken}}
<br>
<button @click="handleLogout">LOGOUT</button>
</div>
</div>
</template>
<script>
import { mapActions, mapGetters } from "vuex";
export default {
data: () => ({
user: "",
password: ""
}),
computed: {
...mapGetters(["getToken", "getUserId"])
},
methods: {
...mapActions(["loginSession", "logoutSession"]),
async handleLogin() {
try {
const { data } = await axios.post("http://js.gl/login", {
user: this.user,
password: this.password
});
this.loginSession(data);
} catch (error) {
console.log(error);
alert("problems?");
}
},
handleLogout() {
this.logoutSession();
}
},
created() {
this.getSession();
}
};
</script>
import Vue from 'vue'
import store from './store'
new Vue({
store,
render: h => h(App)
}).$mount('#app')
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
token: '',
userid: '',
user_type: 0
},
getters: {
getLogin(state) {
return typeof state.token === 'string' && state.token !== ''
},
getToken(state) {
return state.token
},
getUserId(state) {
return state.userid
},
getUserType(state) {
return state.user_type
}
},
actions: {
loginSession(context, data) {
sessionStorage.setItem('session', JSON.stringify(data))
context.commit('setSession', data)
},
getSession(context) {
const session = sessionStorage.getItem('session')
if (session && typeof session === 'string' && session !== '') {
const data = JSON.parse(session)
context.commit('setSession', data)
}
},
logoutSession(context) {
context.commit('logoutSession')
}
},
mutations: {
setSession(state, n) {
state.token = n.token
state.userid = n.userid
state.user_type = n.user_type
},
logoutSession(state) {
sessionStorage.clear()
state.token = ''
state.userid = ''
state.user_type = 0
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment