i am getting the data from a config panel route setting it to the localstorage with vuex , storeJS:
const state = {
message: [],
// console.log(message);
sec: 0,
// other state
};
const getters = {
message: (state) => {
// console.log(this.state.message);
return state.message;
},
sec: (state) => {
return state.sec;
},
// other getters
};
const actions = {
setMessage: ({ commit, state }, inputs) => {
commit(
'SET_MESSAGE',
inputs.map((input) => input.message)
);
return state.message;
},
setSec: ({ commit, state }, newSecVal) => {
commit('SET_TIMEOUT', newSecVal);
return state.sec;
},
// other actions
};
const mutations = {
SET_MESSAGE: (state, newValue) => {
state.message = newValue;
localStorage.setItem('message', JSON.stringify(newValue)); ----->this
},
SET_TIMEOUT: (state, newSecVal) => {
state.sec = newSecVal;
localStorage.setItem('sec', JSON.stringify(newSecVal)); --->this
},
// other mutations
};
export default {
state,
getters,
actions,
mutations,
};
Now i am having a home route where i want to display this ,how can i access that?
I am getting the data (not the localstorage but the regular state data) with Mapgetters and i am using it like that:
computed: {
...mapGetters({
message: "message",
sec: "sec"
}),
how can i tell him that if there is nothing (when a page reloads ) to automaticcally get the data from localstorage. This is my MOunted
mounted() {
this.$store.dispatch("SET_MESSAGE");
this.$store.dispatch("SET_SEC");
},
I will suggest you use this package to keep your state and local storage in sync vuex-persistedstate.
Alternatively, you can set your state like this.
const state = {
message: localStorage.getItem('message') || [],
// console.log(message);
sec: localStorage.getItem('sec') || '',
// other state
};