How to use localstorage and sessionstorage in Vue
This time I will bring you how to use localstorage and sessionstorage in Vue. What are the precautions for using localstorage and sessionstorage in Vue. The following is a practical case. Get up and take a look.
1. Several problems exposed during the use of the project
Everyone directly uses localstorage['aaa']='This is an example string' and these native syntax implementations. This coupling is too high. If one day we need to change the implementation method, or adjust the storage size If you do some control, there will be a lot of code that needs to be modified
If the project is very large, the key names given by everyone 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 for storage key values
Standardize the usage specifications of storage
2.1. Encapsulate a unified method
Encapsulating into methods can reduce coupling, facilitate switching of implementation methods, and control the storage size
Changing the implementation can be achieved by configuring different parameters
Edit the project structure as 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('当前浏览器不支持localStorage!') } var test = '0123456789' 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('test') window.localStorage.setItem('test', sum) console.log(sum.length / 1024 + 'KB') } catch (e) { console.log(sum.length / 1024 + 'KB超出最大限制') clearInterval(show) } }, 0.1) }, // 获取使用了的localstorage的空间 getUsedSpace(){ if (!window.localStorage) { console.log('浏览器不支持localStorage') } var size = 0 for (item in window.localStorage) { if (window.localStorage.hasOwnProperty(item)) { size += window.localStorage.getItem(item).length } } console.log('当前localStorage使用容量为' + (size / 1024).toFixed(2) + 'KB') } }
/* * 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('当前浏览器不支持sessionStorage!') } var test = '0123456789' 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('test') window.sessionStorage.setItem('test', sum) console.log(sum.length / 1024 + 'KB') } catch (e) { console.log(sum.length / 1024 + 'KB超出最大限制') clearInterval(show) } }, 0.1) }, // 获取使用了的localstorage的空间 getUsedSpace(){ if (!window.sessionStorage) { console.log('浏览器不支持sessionStorage') } var size = 0 for (item in window.sessionStorage) { if (window.sessionStorage.hasOwnProperty(item)) { size += window.sessionStorage.getItem(item).length } } console.log('当前sessionStorage使用容量为' + (size / 1024).toFixed(2) + 'KB') } }
/* * 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, add the system affix
to each functional system The namespace specification of a system should be designed in advance, otherwise many people will not follow the rules when it is actually developed
Things used globally should be reflected in the README.md document
Example
* localStorage['SGQ.global.userAuthor']:登录的用户信息都在这里,菜单,组织,集团 * localStorage['SGQ.global.systemName']:登录的系统名称 * localStorage['SGQ.vuex.state']:vuex中的state的存储地址,这里面有所有的的东西 * localStorage['SGQ.wms.warehouse']:wms需要的仓库信息 + localStorage['SGQ.wms.warehouse'].permissionId + localStorage['SGQ.wms.warehouse'].dataResource * localStorage['SGQ.tms.org']:tms需要的网点的信息 + localStorage['SGQ.tms.org'].permissionId + localStorage['SGQ.tms.org'].orgName
2.3. Storage usage specifications
2.3.1. Cause of the problem
This problem arises because we need to log in with permissions, and then when logging in, it keeps reporting that there is insufficient storage space. After checking the reason, we found that the backend returned all the thousands of super-managed data, so that there was not enough space. , and later modified the data content returned by the backend interface to solve this problem.
But what did this incident bring 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
The localstorage storage under boss.hivescm.com 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 the total 10M space of localstorage and sessionstorage under one domain name
2.3.2. storage usage plan
Things used globally, things shared, and things permanently stored are stored in localstorage
Remember to clear things that do not need permanent storage after use
If the amount of data is too large, do not store it locally and obtain it dynamically
You can use Indexeddb with larger storage capacity, but there are compatibility issues
You can set a word limit on the things 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 stored in 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 should be cleaned up in time when exiting the vue component
For example: this.bus.$on('aa') should use this.bus.$off('aa') to unload the event
3.2. 字符长短获取
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
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

After long pressing the play button of the speaker, connect to wifi in the software and you can use it. Tutorial Applicable Model: Xiaomi 12 System: EMUI11.0 Version: Xiaoai Classmate 2.4.21 Analysis 1 First find the play button of the speaker, and press and hold to enter the network distribution mode. 2 Log in to your Xiaomi account in the Xiaoai Speaker software on your phone and click to add a new Xiaoai Speaker. 3. After entering the name and password of the wifi, you can call Xiao Ai to use it. Supplement: What functions does Xiaoai Speaker have? 1 Xiaoai Speaker has system functions, social functions, entertainment functions, knowledge functions, life functions, smart home, and training plans. Summary/Notes: The Xiao Ai App must be installed on your mobile phone in advance for easy connection and use.
