search
HomeWeb Front-endJS TutorialHow to use localstorage and sessionstorage in Vue

How to use localstorage and sessionstorage in Vue

Jun 19, 2018 am 10:08 AM
localstoragesessionstoragevue

This article mainly introduces the detailed usage and experience of localstorage and sessionstorage in Vue. Friends in need can follow the editor for reference and study.

1. Several problems exposed in the use of the project

Everyone directly uses localstorage['aaa']='This is a sample string' these native Syntax implementation, this coupling degree is too high. If one day we need to change the implementation method, or do some control on the storage size, then there will be a lot of code that needs to be modified.

The project is very big, so everyone has to start the key The name will inevitably be repeated, and this will also cause global pollution

Because the use of localstorage is not standardized, it results in waste and insufficient storage space

2. Solution

Encapsulate the usage of storage and handle it uniformly

Standardize the naming rules of the key value of storage
Standardize the usage of storage

2.1. Encapsulate the unified method

Encapsulating the method can reduce coupling, facilitate switching of implementation methods, and control the storage size

Changing the implementation can be achieved by configuring different parameters

Edit as shown The project structure shown

Code implementation

/*
 * storage.js
 */
/*
 * @Author: 石国庆
 * @Desc: 本地数据存储方法封装
 * @Date: 2017.11.14
 * @Ref:
 *  https://github.com/WQTeam/web-storage-cache
 *  https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage
 * @Explain:为了不new对象,只能多写几遍
 * @Example:
 *
 * 1、LocalStorage的使用
 * import storage from '@/utils/storage.js'
 * storage.setItem('shiguoqing0',[1,2,3,4,5,6])
 * storage.setItem('shiguoqing1',{userId:'dfdf',token:11232323})
 * storage.setItem('shiguoqing2','dfdfdf')
 * console.log(storage.getItem('shiguoqing0'))
 * console.log(storage.getItem('shiguoqing1'))
 * console.log(storage.getItem('shiguoqing2'))
 * storage.removeItem('shiguoqing2')
 *
 *
 * 2、SessionStorage的使用
 * storage.setItem('shiguoqing0',[1,2,3,4,5,6],{type:'session'})
 *
 * */
// TODO:其他方法的实现
// TODO:超时时间的设置
/*
 * 方法实现
 * */
import local from './storage/localstorage.js'
import session from './storage/session.js'
import cookies from './storage/cookies.js'
import json from './storage/json.js'
/*
* 函数体
* */
let storage= {
 config:{
  type:'local',// local,session,cookies,json
  expires:new Date().getTime() + 100 * 24 * 60 * 60 * 1000
 },
 getStorage(options){
  let config={}
  if(options){
   config=Object.assign({},this.config,options)
  }else{
   config=this.config
  }
  return this.createStorage(config.type)
 },
 createStorage(name){
  switch(name){
   case 'local':return local;break
   case 'session':return session;break
   case 'cookies':return cookies;break
   case 'json':return json;break
  }
 },
 getItem(key,options){
  let store=this.getStorage(options)
  return store.getItem(key)
 },
 setItem(key, value,options){
  let store=this.getStorage(options)
  store.setItem(key,value)
 },
 removeItem(key,options){
  let store=this.getStorage(options)
  store.removeItem(key)
 },
 getAll(){},
 clear(options){
  let store=this.getStorage(options)
  store.clear()
 },
 key(n){},
 lenght(){},
 has(key){},
 forEach(cb){},
 deleteAllExpires(){},
 // 获取最大存储空间:只有LocalStorage和SessionStorage可以使用这个方法
 getMaxSpace(options){
  let store=this.getStorage(options)
  store.getMaxSpace()
 },
 // 获取使用了的空间:只有LocalStorage和SessionStorage可以使用这个方法
 getUsedSpace(options){
  let store=this.getStorage(options)
  store.getUsedSpace()
 }
}
export default storage
// https://segmentfault.com/a/1190000002458488
// 5、遍历localStorage存储的key
//  .length 数据总量,例:localStorage.length
//  .key(index) 获取key,例:var key=localStorage.key(index);
// 备注:localStorage存数的数据是不能跨浏览器共用的,一个浏览器只能读取各自浏览器的数据,储存空间5M。
// 超时设置
// function(st, key, value, expires) {
//  if (st == 'l') {
//   st = window.localStorage;
//   expires = expires || 60;
//  } else {
//   st = window.sessionStorage;
//   expires = expires || 5;
//  }
//  if (typeof value != 'undefined') {
//   try {
//    return st.setItem(key, JSON.stringify({
//     data: value,
//     expires: new Date().getTime() + expires * 1000 * 60
//    }));
//   } catch (e) {}
//  } else {
//   var result = JSON.parse(st.getItem(key) || '{}');
//   if (result && new Date().getTime() < result.expires) {
//    return result.data;
//   } else {
//    st.removeItem(key);
//    return null;
//   }
//  }
// }
/*
 * localstorage.js
 * localstorage的实现
 */
// 这个有点奇怪,文件名称叫local.js不能按照js文件解析
export default {
 getItem(key){
  let item = localStorage.getItem(key)
  // 这点要判断是字符串还是对象
  let result = /^[{\[].*[}\]]$/g.test(item)
  if (result) {
   return JSON.parse(item)
  } else {
   return item
  }
 },
 setItem(key, value){
  // 这点要判断是字符串还是对象
  if (typeof value == "string") {
   localStorage.setItem(key, value)
  } else {
   let item = JSON.stringify(value)
   localStorage.setItem(key, item)
  }
 },
 removeItem(key){
  localStorage.removeItem(key)
 },
 getAll(){},
 clear(){
  localStorage.clear()
 },
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){},
 // 获取localstorage最大存储容量
 getMaxSpace(){
  if (!window.localStorage) {
   console.log(&#39;当前浏览器不支持localStorage!&#39;)
  }
  var test = &#39;0123456789&#39;
  var add = function (num) {
   num += num
   if (num.length == 10240) {
    test = num
    return
   }
   add(num)
  }
  add(test)
  var sum = test
  var show = setInterval(function () {
   sum += test
   try {
    window.localStorage.removeItem(&#39;test&#39;)
    window.localStorage.setItem(&#39;test&#39;, sum)
    console.log(sum.length / 1024 + &#39;KB&#39;)
   } catch (e) {
    console.log(sum.length / 1024 + &#39;KB超出最大限制&#39;)
    clearInterval(show)
   }
  }, 0.1)
 },
 // 获取使用了的localstorage的空间
 getUsedSpace(){
  if (!window.localStorage) {
   console.log(&#39;浏览器不支持localStorage&#39;)
  }
  var size = 0
  for (item in window.localStorage) {
   if (window.localStorage.hasOwnProperty(item)) {
    size += window.localStorage.getItem(item).length
   }
  }
  console.log(&#39;当前localStorage使用容量为&#39; + (size / 1024).toFixed(2) + &#39;KB&#39;)
 }
}
/*
 * session.js
 * sessionstorage的实现
 */
export default {
 getItem(key){
  let item = sessionStorage.getItem(key)
  // 这点要判断是字符串还是对象
  let result = /^[{\[].*[}\]]$/g.test(item)
  if (result) {
   return JSON.parse(item)
  } else {
   return item
  }
 },
 setItem(key, value){
  // 这点要判断是字符串还是对象
  if (typeof value == "string") {
   sessionStorage.setItem(key, value)
  } else {
   let item = JSON.stringify(value)
   sessionStorage.setItem(key, item)
  }
 },
 removeItem(key){
  sessionStorage.removeItem(key)
 },
 getAll(){},
 clear(){
  sessionStorage.clear()
 },
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){},
 // 获取localstorage最大存储容量
 getMaxSpace(){
  if (!window.sessionStorage) {
   console.log(&#39;当前浏览器不支持sessionStorage!&#39;)
  }
  var test = &#39;0123456789&#39;
  var add = function (num) {
   num += num
   if (num.length == 10240) {
    test = num
    return
   }
   add(num)
  }
  add(test)
  var sum = test
  var show = setInterval(function () {
   sum += test
   try {
    window.sessionStorage.removeItem(&#39;test&#39;)
    window.sessionStorage.setItem(&#39;test&#39;, sum)
    console.log(sum.length / 1024 + &#39;KB&#39;)
   } catch (e) {
    console.log(sum.length / 1024 + &#39;KB超出最大限制&#39;)
    clearInterval(show)
   }
  }, 0.1)
 },
 // 获取使用了的localstorage的空间
 getUsedSpace(){
  if (!window.sessionStorage) {
   console.log(&#39;浏览器不支持sessionStorage&#39;)
  }
  var size = 0
  for (item in window.sessionStorage) {
   if (window.sessionStorage.hasOwnProperty(item)) {
    size += window.sessionStorage.getItem(item).length
   }
  }
  console.log(&#39;当前sessionStorage使用容量为&#39; + (size / 1024).toFixed(2) + &#39;KB&#39;)
 }
}
/*
 * cookies.js
 * cooikes的实现,这辈子估计没有时间实现了
 */
export default {
 getItem(key){},
 setItem(key, value){},
 removeItem(key){},
 getAll(){},
 clear(){},
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){}
}
/*
 * json.js
 * json的实现,这辈子估计也没有时间实现了
 */
export default {
 getItem(key){},
 setItem(key, value){},
 removeItem(key){},
 getAll(){},
 clear(){},
 key(n){},
 forEach(cb){},
 has(key){},
 deleteAllExpires(){}
}

2.2. Standardize the use of namespace

In order to prevent key value pollution, we can use the namespace reasonably

We can define a namespace, but we cannot store a lot of data in the same object, so the amount of subsequent operations will be too large

For example, the global one is under global

For example, the addition of each functional system System affixes

The namespace specification of a system should be designed in advance, otherwise many people will use it without following the rules during actual development

Things used globally must be reflected in the README.md document Come out

Example

* localStorage[&#39;SGQ.global.userAuthor&#39;]:登录的用户信息都在这里,菜单,组织,集团
* localStorage[&#39;SGQ.global.systemName&#39;]:登录的系统名称
* localStorage[&#39;SGQ.vuex.state&#39;]:vuex中的state的存储地址,这里面有所有的的东西
* localStorage[&#39;SGQ.wms.warehouse&#39;]:wms需要的仓库信息
+ localStorage[&#39;SGQ.wms.warehouse&#39;].permissionId
+ localStorage[&#39;SGQ.wms.warehouse&#39;].dataResource
* localStorage[&#39;SGQ.tms.org&#39;]:tms需要的网点的信息
+ localStorage[&#39;SGQ.tms.org&#39;].permissionId
+ localStorage[&#39;SGQ.tms.org&#39;].orgName

2.3. Storage usage specifications

2.3.1. Cause of the problem

This problem occurs because we need to do permissions After logging in, I kept getting reports of insufficient storage space. After checking the reason, I found that the backend returned all the thousands of super-managed data, which was not enough. Later, I modified the data returned by the backend interface. Content solves this problem.

But what has this incident brought us to think about?

The storage capacity of localstorage and sessionstorage is basically 5M in different browsers

The storage of localstorage and sessionstorage follows the domain name

localstorage under boss.hivescm.com The storage is 5M

The localstorage storage under b2b.hivescm.com is also 5M

Even if the problem is solved this time, we should make a plan to make full use of localstorage and sessionstorage under one domain name. Total 10M space

2.3.2. Storage usage plan

Things used globally, shared, and permanently stored are stored in localstorage

No need for permanent storage Remember to clear things in time after using them

If the amount of data is too large, do not store it locally and change it to dynamic acquisition

You can use Indexeddb with larger storage capacity, but there is compatibility Question

You can limit the number of words to be stored in storage in the implementation plan

Make full and reasonable use of the H5 features of sessionstorage and localstorage

For example: list data is stored in In fact, vuex will also be stored in localstorage

For example: some data for form verification uses sessionstorage

3. Others

3.1. Extension

This can be deduced to the processing of events. Useless events must be cleaned up in time when exiting the vue component.

For example: this.bus.$on('aa') should be used this.bus.$off('aa') uninstall event

3.2. Character length acquisition

var len = 0
for (var i = 0; i < val.length; i++) {
 if (val[i].match(/[^\x00-\xff]/ig) != null) //全角
  len += 2 //如果是全角,占用两个字节 如果mysql中某字段是text, 如果设置编码为utf-8,那么一个中文是占3个字节, gbk是两个字节
 else
  len += 1 //半角占用一个字节
}
return len

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

JS plug-in for Web forms (high-quality recommendation)

How to implement online customer service function in jQuery

How to dynamically add to the list in jQuery

About optimization configuration issues in Webpack

In How to build Electron applications in Webpack

Issues about unsafe image paths using Angular4

How to implement the cross coordinates following mouse effect in JS

How to use EasyUI window in jQuery

How to use laydate.js date plug-in in Angular4.0

How to implement label scrolling switching in JS

The above is the detailed content of How to use localstorage and sessionstorage in Vue. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.