Using vuex-persisted state would be the best use case for your scenario.
I will walk you through the process of using vuex-persisted state.
- Open command line,
cd
to your project directory, then enter npm install --save vuex-persistedstate
. This will install vuex-persistedstate into your project dependencoes.
- Now in your store.js file or wherever your defined your vuex store, add the vuex-persistedstate plugin
import createPersistedState from "vuex-persistedstate";
import * as Cookie from "js-cookie";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
user: {
name: "john doe",
age: " 16",
},
loggedIn: false,
hobbies: ["eating", "partying"],
},
plugins: [
createPersistedState({
paths: ["user", "loggedIn"],
getState: (key) => Cookie.getJSON(key),
setState: (key, state) =>
Cookie.set(key, state, { expires: 1, secure: false }),
}),
],
});
- You also need js-cookie package which makes handling cookies easier. Use
npm install --save js-cookie
.
- The paths property says which parts of the state to persist, in our case save as cookies.If no path property is given, then the whole state is persisted
- From the above example we have mentioned the paths
paths: ['user', 'loggedIn']
, so only user and loggedIn properties of the state are saved in cookies not hobbies.
- In case you are using modules in your store, the way of defining the pats to persist would be as follows:
import createPersistedState from "vuex-persistedstate";
import * as Cookie from "js-cookie";
import myModule from "./myModule";
import myAnotherModule from "./myAnotherModule";
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
user: {
name: "john doe",
age: " 16",
},
loggedIn: false,
hobbies: ["eating", "partying"],
},
modules: {
myModule,
myAnotherModule,
},
plugins: [
createPersistedState({
paths: ["user", "loggedIn", "myModule.<nameOfThePropretyInState>"],
getState: (key) => Cookie.getJSON(key),
setState: (key, state) =>
Cookie.set(key, state, { expires: 1, secure: false }),
}),
],
});
In your paths you will refer to the module's property in the state you want to persist. In the above example, the property of the state that you mention of myModule is persisted. myAnotherModule state is not saved since it is not mentioned in the paths.
That's it . If you want to customize the way you use vuex-persisted state and js-cookie, have a look at their documentation.
If you want to check whether your desired state is saved in cookies then you can console log your cookies like this: console.log(document.cookie
in your App.vue created() lifecycle hook