Vuex refresh data disappeared problem

Preface

Vuex may be used in large single-page projects built by vue. Vuex's state storage is responsive. When a Vue component reads the state from the store, if the state in the store changes, the corresponding component will be updated accordingly. But there is a problem: the data stored in vuex is only in the page, which is equivalent to the global variables we defined. After refreshing, the data inside will be restored to the initial state. But this situation is sometimes not what we want. For example, if the user is already logged in, I put the login status in the state. Once I refresh the page, do I need to log in again? The added data in the shopping cart should be re-added once it is refreshed?

Solutions:

Monitor whether the page is refreshed. If the page is refreshed, store the state object in sessionStorage/localStorage. After the page is opened, determine whether there is a state object in sessionStorage/localStorage. If it exists, it means that the page has been refreshed. The data stored in sessionStorage/localStorage is taken out to assign a value to the state in vuex. If it does not exist, it means that it is opened for the first time, and the initial value of state defined in vuex is taken.

Introduction to sessionStorage and localStorage

H5 provides our commonly used localStorage and sessionStorage. The difference between the two: the localStorage life cycle is permanent, which means that unless the user clears the localStorage information on the UI provided by the browser, the information will always exist. The storage data size is generally 5MB, and it is only stored in the client (ie browser), and does not participate in the communication with the server. sessionStorage is only valid in the current session and will be cleared after closing the page or browser. The storage data size is generally 5MB, and it is only stored in the client (ie browser), and does not participate in the communication with the server. The source interface can be accepted, and it can also be encapsulated again to have better support for Object and Array. Browser support In addition to IE7 and below, other standard browsers are fully supported (ie and FF need to run in the web server)

Guess you like

Origin blog.csdn.net/weixin_40648700/article/details/112005539