SoFunction
Updated on 2025-04-06

Detailed explanation of how to use localStorage in vue

What is localStorage

For browsers, using Web Storage to store key-values ​​is more intuitive and has a larger capacity. It includes two types: localStorage and sessionStorage

(Temporary Storage): Maintain a storage area for each data source, which exists during browser opening, including page reloading

(Long-term storage): Like sessionStorage, but after the browser is closed, the data will still exist

So I encountered a pit last time when I used cookies. After setting it, I would not get it if I access the session immediately. It hurts. I still need to refresh it. The reason is:

When we first access the page where cookies are set, the server will send the set cookie value through the response header, telling the browser to store the cookie in the local corresponding folder (note: the cookie was not stored locally during the first visit, so the value cannot be obtained at this time);

When you access the second time (or all visits before expiration after setting the cookie), you will carry the cookie value in the request header information. (I came here on Baidu, but I haven’t understood it thoroughly yet, so I’ll move it here first).

The method to implement local storage in vue: localStorage. In HTML5, a new localStorage feature has been added. This feature is mainly used as local storage, which solves the problem of insufficient cookie storage space (the storage space of each cookie in cookies is 4k). In localStorage, the general browser supports 5M size, which will be different in different browsers.

(1).Storing data

('accessToken', 'Bearer ' + )

(2). Take out the data

('accessToken')

(3). Delete stored data

 ('accessToken')

(4). Change the data

('accessToken', 'After changing' + )

There are two things to note when using:

. localStorage is not readable under the browser's privacy mode.
. localStorage is essentially a reading of strings. When there is json format, () needs to be converted into strings.
. localStorage cannot be caught by crawlers

Note

  • The validity period of localStorage is permanent. A general browser can store about 5MB. The sessionStorage api is the same as localStorage.
  • The default validity period of sessionStorage is the browser's session time (that is, it disappears after the tab is closed).
  • The localStorage scope is protocol, hostname, and port. (Theoretically, it is not artificially deleted and has always been present in the device)
  • The sessionStorage scope is window, protocol, hostname, and port.

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.