Save store to localStorage

This commit is contained in:
Jan Bader 2022-01-22 16:10:46 +00:00
parent 15ab8a3dac
commit 4af82805ff
3 changed files with 47 additions and 5 deletions

View File

@ -1,11 +1,26 @@
<script setup> <script>
// This starter template is using Vue 3 <script setup> SFCs // This starter template is using Vue 3 <script setup> SFCs
// Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup // Check out https://v3.vuejs.org/api/sfc-script-setup.html#sfc-script-setup
export default {
calculated: {
loggedIn() {
return this.$store.Session.Token;
}
},
beforeCreate () {
this.$store.commit("initializeStore");
}
}
</script> </script>
<template> <template>
<img alt="Vue logo" src="./assets/logo.png" /> <img alt="Vue logo" src="./assets/logo.png" />
<router-link to="/uiae">Go to Bar</router-link> <ul>
<li v-if="loggedIn"><router-link to="/login">Login</router-link></li>
<li v-if="!loggedIn"><router-link to="/logout">Logout</router-link></li>
<li v-if="!loggedIn"><router-link to="/">Dashboard</router-link></li>
</ul>
<router-view></router-view> <router-view></router-view>
</template> </template>

View File

@ -6,20 +6,45 @@ import router from './router/index.js'
const store = createStore({ const store = createStore({
state () { state () {
return { return {
Session: {
Token: null,
User: null
},
Budgets: [], Budgets: [],
CurrentBudget: null, CurrentBudget: null,
} }
}, },
mutations: { mutations: {
initializeStore(state) {
if(localStorage.getItem("store")){
this.replaceState(
Object.assign(state, JSON.parse(localStorage.getItem("store")))
);
}
},
getDashboard (state) { getDashboard (state) {
fetch("/api/v1/dashboard") fetch("/api/v1/dashboard", {
headers: {
'Authorization': 'Bearer ' + state.Token
}
})
.then(x => x.json()) .then(x => x.json())
.then(x => console.log(x)) .then(x => state.Budgets = x.Budgets)
.then(x => state.Budgets = x.Budgets); .then(x => console.log(state.Budgets));
},
setTitle (state, title) {
document.title = "Budgeteer - " + title;
},
setToken(state, token) {
state.Token = token;
} }
} }
}) })
store.subscribe((mutation, state) => {
localStorage.setItem("store", JSON.stringify(state));
})
const app = createApp(App) const app = createApp(App)
app.use(router) app.use(router)
app.use(store) app.use(store)

View File

@ -1,9 +1,11 @@
import { createRouter, createWebHashHistory } from 'vue-router' import { createRouter, createWebHashHistory } from 'vue-router'
import HelloWorld from '../components/HelloWorld.vue'; import HelloWorld from '../components/HelloWorld.vue';
import Dashboard from '../pages/Dashboard.vue'; import Dashboard from '../pages/Dashboard.vue';
import Login from '../pages/Login.vue';
const routes = [ const routes = [
{ path: '/', name: 'Index', component: Dashboard }, { path: '/', name: 'Index', component: Dashboard },
{ path: '/login', name: 'Login', component: Login },
{ path: '/uiae', name: 'Home', component: HelloWorld }, { path: '/uiae', name: 'Home', component: HelloWorld },
] ]