Ideas and codes for implementing Vuex data persistence

Ideas and codes for implementing Vuex data persistence

What is vuex

vuex: is a state manager developed specifically for vue.js, which uses centralized storage of all component states

Five attributes: state, getters, mutations, actions, module

Basic use:

Create a new store.js file, finally introduce it in main.js, and mount it to the real column

   import Vue from 'vue'
   import Vuex from 'vuex'
   Vue.use(Vuex)
   const state = {}
   const getters = {}
   const mutations = {}
   const actions = {}
   export default new Vuex.Store({
       state,
       getters,
       mutations,
       actions
   
   })

state attribute: stores the state, such as the data you want to store

Getters: Similar to shared properties, you can use this.$store.getters to get the data stored in the state

mutations: The only way to change the state is by submitting mutations, this.$store.commit()

Actions: One-step mutations, which can be distributed through dispatch to change the state

Vuex data persistence

As we all know, Vuex data is stored in memory, and these data will be lost if you refresh the web page. We hope that some data can still be retained after refreshing, which requires storing the data. Here is a record of using localStorage to persist the data in Vuex.

Implementation ideas

  • Because the data in the state can theoretically only be updated through mutation, you can listen to mutation events. After each event is executed, convert the entire state data at this time into a string and store it in localStorage.
  • When the page initializes the state, read the localStorage value, convert it back to JSON, and merge it into the current state.
  • This method is just a simple implementation and is only applicable to simple objects. For complex objects, converting them back to JSON may lose the corresponding events and methods. You can consider storing them in other ways later.

Code

Plugins:

export default (options = {}) => {
  const storage = options.storage || (window && window.localStorage);
  const key = options.key || "vuex";

  // Get the value of state const getState = (key, storage) => {
    const value = storage.getItem(key);
    try {
      return typeof value !== "undefined" ? JSON.parse(value) : undefined;
    } catch (err) {
      console.warn(err);
    }
    return undefined;
  };

  // Set the value of state const setState = (key, state, storage) =>
    storage.setItem(key, JSON.stringify(state));

  return (store) => {
    // Get data during initialization. If any, replace the original vuex state const data = Object.assign(store.state, getState(key, storage));
    if (data) {
      store.replaceState(data);
    }

    // Subscribe to store mutation. The handler is called after each mutation is completed, receiving the mutation and the state after the mutation as parameters store.subscribe((mutation, state) => {
      setState(key, state, storage);
    });
  };
};

Calling method:

import VuexPersist from "@/plugins/VuexPersist";

export default createStore({
  plugins: [VuexPersist()],
});

Summarize

This is the end of this article about the implementation of Vuex data persistence. For more relevant Vuex data persistence content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to implement data persistence using the vuex third-party package
  • Two implementation solutions for vuex data persistence
  • VUEX data persistence, example of re-acquisition after refresh
  • Vuex implements data state persistence
  • How to implement a simple vuex persistence tool
  • Detailed explanation of vuex persistence in practical application of vue

<<:  Linux common text processing commands and vim text editor

>>:  Detailed explanation of the error problem of case when statement

Recommend

innodb_flush_method value method (example explanation)

Several typical values ​​of innodb_flush_method f...

JS thoroughly understands GMT and UTC time zones

Table of contents Preface 1. GMT What is GMT Hist...

Detailed explanation of computed properties in Vue

Table of contents Interpolation Expressions metho...

Make your website run fast

Does performance really matter? Performance is im...

How to set up the use of Chinese input method in Ubuntu 18.04

In the latest version of Ubuntu, users no longer ...

Install mysql5.7 on Ubuntu 18.04

Ubuntu 18.04 installs mysql 5.7 for your referenc...

js to achieve simple front-end paging effect

Some projects have relatively simple business, bu...

Centos7 install mysql5.6.29 shell script

This article shares the shell script of mysql5.6....

Use vue3 to implement a human-cat communication applet

Table of contents Preface Initialize the project ...

Ant designing vue table to achieve a complete example of scalable columns

Perfect solution to the scalable column problem o...

Simple implementation of Mysql add, delete, modify and query statements

Simple implementation of Mysql add, delete, modif...

How to write high-quality JavaScript code

Table of contents 1. Easy to read code 1. Unified...