Vuex interpretation and solution to the problem of no data after refreshing in the store

Vuex is a state management model specially developed for vue.js applications. It can be understood as shared data. It has five default states:

  • state: storage state (variable)
  • getters: recompilation before data acquisition, which can be understood as the calculation property of state. We use $sotre.getters.fun() in the component
  • mutations: modify the state and are synchronous. Use $store.commit('', params) in the component. This is similar to custom events in our components.
  • actions: asynchronous operations. Used in components is $store.dispath('')
  • modules: submodules of the store, used for developing large-scale projects and facilitating state management. We won't explain it here, it's the same as above.

"Modify State" is split into two parts: the view triggers the Action, and the Action triggers the Mutation.

Mutation: Focus on modifying State, which is theoretically the only way to modify State. Must be executed synchronously (equivalent to method).

Action: business code, asynchronous request. It can be asynchronous, but cannot directly manipulate State. (equivalent to axios in created)

Store: Define variables (equivalent to data).

Example:

1. First import the corresponding file in the store.js file and define the variables

import View from 'view';

import Vuex from 'vuex';

import mutations from './mutations';

import actions from './actions';

Vue.use(Vuex);

export default new Vuex.Store({

    state: {

         userInfo: {}

    }

    mutations,

    actions

});

2. Define the function to modify info in mutations.js

3. Write the function of asynchronous request in action.js

Note: When the page is refreshed, the vue instance will be reloaded, and the store will be reset. If the variable is not modified through the current page, there will be no data after the refresh. Therefore, the store can be stored in local localStorage, sessionStorage, and cookies before the definition is refreshed. localStorage is permanent storage. When the page is reopened, the data of the last opened page will be read. SessionStorage is stored until it is closed. Cookies are not suitable for storing large amounts of data. . You can choose an appropriate method according to your own needs to solve the refresh problem. The following uses sessionStorage as an example:

export default new Vuex.Store({

    state:sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')) : {

        userInfo: {},

    },

    mutations,

    actions

});

That is, the state data is first stored in sessionStorage, and each time the state is obtained, it is taken from the sessionStore.

Guess you like

Origin blog.csdn.net/Anna_lhy/article/details/103183834