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

How to run multiple MySQL instances in Windows

Preface In Windows, you can start multiple MySQL ...

How to run Hadoop and create images in Docker

Reinventing the wheel, here we use repackaging to...

Solution to VMware virtual machine no network

Table of contents 1. Problem Description 2. Probl...

Linux kernel device driver kernel debugging technical notes collation

/****************** * Kernel debugging technology...

Vue state management: using Pinia instead of Vuex

Table of contents 1. What is Pinia? 2. Pinia is e...

Detailed explanation of how to use several timers in CocosCreator

1. setTimeOut Print abc after 3 seconds. Execute ...

JavaScript canvas to achieve colorful clock effect

Use canvas to write a colorful clock! 1. Title (1...

MySQL operations: JSON data type operations

In the previous article, we introduced the detail...

Native JS to implement paging click control

This is an interview question, which requires the...

MySQL database terminal - common operation command codes

Table of contents 1. Add users 2. Change the user...

How to use Axios asynchronous request API in Vue

Table of contents Setting up a basic HTTP request...

How to install Solr 8.6.2 in Docker and configure the Chinese word segmenter

1. Environment version Docker version 19.03.12 ce...

How does Vue track data changes?

Table of contents background example Misconceptio...

Do you know the common MySQL design errors?

Thanks to the development of the Internet, we can...