This article focuses on how to make Vuex data persistent.

LocalStorage or sessionStorage is used by browsers to persist data.

Both localStorage and sessionStorage can save data to the browser. LocalStorage does not expire, unless cleared or outsized, and sessionStorage is cleared once the browser closes.

How Vuex and localStorage or sessionStorage are combined?

Store plug-in

Here we use a plugin called Store, of course, it is not necessary, but you have to write set, get slightly troublesome to write. Store plug-in is the Storage set, get package, use more convenient.

store2

Since 2.x, features have also become more powerful

// === store(key, data); store.set(key, data[, overwrite]); // === store({key: data, key2: data}); store.setAll(data[, overwrite]); // === store(key); store.get(key[, alt]); // === store(); store.getAll([fillObj]); // === store(key, fn[, alt]); store.transact(key, fn[, alt]); // === store(false); store.clear(); // returns true or false store.has(key); // removes key and its data, then returns the data store.remove(key); // fn receives key and data (or fill), return false to exit early store.each(fn[, fill]); // concats, merges, or adds new value into existing one store.add(key, data); // returns array of keys store.keys([fillList]); // number of keys, not length of data store.size(); // clears *ALL* areas (but still namespace sensitive) store.clearAll(); Copy the codeCopy the code

Let’s take a look at an example

Storage file Example

Create a storage.js file

import storage from 'store'; // Cache data key const WEB_NAME = 'WEB_NAME'; export const storage = { set setLocalStorageName(val) { if (! val) { storage.remove(WEB_NAME); } else { storage.set(WEB_NAME, val); } }, get getLocalStorageName() { return storage.get(WEB_NAME); }} Copy the codeCopy the code

Sample Store file

Create a new store.js file and import the storage.js file above

import Vue from 'vue' import Vuex from 'vuex' import { storage } from './storage'; Vuex. use(Vuex) const store = new vuex. store ({state: { storage.getLocalStorageName || '' }, mutations: {setData (state, data) {/ / get data has, to the state and data storage is placed inside the state name = data storage. SetLocalStorageName = data; }}, actions: {getData ({commit, state}, params) {let name = 'Vuex+localStorage data state persistence '; Commit ('setData', name)}}) export default Store Copies the codeCopy the code

So when using Vuex State, forcing a page refresh will not clear the name value, only manually clear the train set null value can clear the name value.

Application scenarios of Vuex data state persistence

1, shopping cart for example, after you add goods to the shopping cart, do not save to the background, the front to save, you can through this way.

2. Session Status After authorized login, the token can be stored with Vuex+sessionStorage.

Vuex+localStorage Data state persistence