Detailed explanation of Vue's caching method example

Detailed explanation of Vue's caching method example

Recently, a new requirement "front-end cache" was created

Requirement background: To solve the problem of high-frequency repeated filling of forms, it is required to automatically fill in the last entered data when opening the page, and the data storage period is one week (valid for 7 days).
When it comes to caching, the first thing that comes to mind is localstorage and sessionStorage

sessionStorage

Also known as session cache, the data is deleted when the user closes the browser window;

sessionStorage.setItem("key","value");//Storage sessionStorage.getItems("key");//Press to get the value sessionStorage.removeItems("key");//Press key to delete a single sessionStorage.clear();//Delete all data sessionStorage.length;//Get the number of data sessionStorage.valueOf();//Get all values

localstorage

There is no time limit for the stored data. As long as it is not deleted, it will exist.

localstorage.setItem("key","value");//Save data localstorage.getItem("key");//Read data localstorage.removeItem("key",);//Delete single data localstorage.clear();//Delete all data localstorage.key(index);//Get the key of a certain index
Both key and value must be strings. Web Storage API can only operate on strings.

Since sessionStorage data will be cleared when the browser window is closed, it is not applicable to the needs I want to develop. If we only consider these two solutions, localstorage seems to be relatively suitable, but if localstorage is used for storage and expiration is set, it will be more troublesome from a code perspective.

Specific implementation ideas of localstorage

1. Add timestamp when storing data

When the data is large, you can use localstorage to write a time when storing data, and compare it with the current time when getting it.

In project development, we can write a common method to add a timestamp when storing

  export function setLocalStorageAndTime (key, value) {
  window.localStorage.setItem(key, JSON.stringify({ data: value, time: new Date().getTime() }))
  }

Application in the project

  If there is data, store it again setLocalStorageAndTime('XXX', {name: 'XXX'})

2. Compare with the current time when obtaining data

export function getLocalStorageAndTime (key, exp = 86400000) {
 // Get data let data = window.localStorage.getItem(key)
 if (!data) return null
 let dataObj = JSON.parse(data)
 // Compare with expiration time if (new Date().getTime() - dataObj.time > exp) {
  // Return null if expired
  removeLocalStorage(key)
  console.log('Information has expired')
  return null
 } else {
  return dataObj.data
 }
}

The biggest characteristic of programmers is laziness. They will never miss a plug-in and will never type a CV manually if possible. Because it is too cumbersome to write, I decisively gave up using localstorage and looked for a simpler and more convenient method. I finally chose Vue.ls through the recommendation of a colleague, so let me introduce Vue.ls.

Vue.ls

A local storage method encapsulated by Vue. A Vue plugin for using local Storage, session Storage, and memory Storage from within a Vue context. It's easy to use, and the API description is comprehensive.

Install

NPM

npm install vue-ls --save

Yarn

yarn add vue-ls

use

Vue-ls Storage API
import Storage from 'vue-ls';
 
options = {
 namespace: 'vuejs__', // key prefix name: 'ls', // Name the Vue variable.[ls] or this.[$ls],
 storage: 'local', // Storage name: session, local, memory
};
 
Vue.use(Storage, options);
// or Vue.use(Storage);
 
new Vue({
  el: '#app',
  mounted: function() {
    Vue.ls.set('foo', 'boo');
    // Set validity period Vue.ls.set('foo', 'boo', 60 * 60 * 1000); // Valid for 1 hour Vue.ls.get('foo');
    Vue.ls.get('boo', 10); // If boo is not set, return the default value 10 
    
    let callback = (val, oldVal, uri) => {
     console.log('localStorage change', val);
    } 
    
    Vue.ls.on('foo', callback) // Detect changes to the foo key and trigger the callback Vue.ls.off('foo', callback) // Do not detect Vue.ls.remove('foo'); // Remove }
});

Global

Vue.ls

Context

this.$ls

API Description

Vue.ls.get(name, def)

Returns the value of name in storage. Internally parse the value from JSON before returning

def: default is null, if not set, returns name.
Vue.ls.set(name, value, expire)

Set the value of name in storage and convert the value into JSON

expire: default is null, name validity period is in milliseconds

Vue.ls.remove(name)

Remove name from storage. Returns true if removed successfully, false otherwise.

Vue.ls.clear()

Clear storage.

Vue.ls.on(name, callback)

Continue to monitor changes to name on other tags, triggering callback when changes occur, passing the following parameters:

  • newValue: name in the current storage, parsed from the persistent JSON
  • oldValue: name in the old storage, parsed from the persistent JSON
  • url: Modify the URL from the tab

Vue.ls.off(name, callback)

Remove the previous listener Vue.ls.on(name, callback)

Practice

Storage: key-value pair format, the last parameter is the validity period

Value: The parameter is the key to be stored

View: The stored data can be viewed in localstorage

Summarize

localstorage (local storage) is stored locally as a file for permanent storage; sessionstorage (session storage) is for temporary storage; Vue.ls is a local storage method encapsulated by Vue, which is simple, convenient and easy to use. localStorage and sessionStorage can only store string types. For complex objects, you can use the stringify and parse methods of the JSON objects provided by ECMAScript to process them.

This is the end of this article about Vue's caching method. For more relevant Vue caching method content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Example of forcibly clearing the page cache in a Vue project
  • Detailed explanation of the best solution for implementing caching in Vue projects
  • Detailed explanation of Vue's page cache problem (based on 2.0)
  • Detailed explanation of component caching in Vue
  • Detailed explanation of the integration strategy of Vuex and front-end cache
  • Detailed explanation of vue specified component cache instance
  • How to implement page caching and non-caching in Vue2.0

<<:  win10 mysql 5.6.35 winx64 free installation version configuration tutorial

>>:  How to set static IP for Ubuntu 18.04 Server

Recommend

Implementing carousel with native JavaScript

This article shares the specific code for impleme...

How to manage large file uploads and breakpoint resume based on js

Table of contents Preface Front-end structure Bac...

avue-crud implementation example of multi-level complex dynamic header

Table of contents Preface Background data splicin...

Install ethereum/Ethereum from scratch under CentOS7

Table of contents Preface Add sudo write permissi...

Multi-service image packaging operation of Dockerfile under supervisor

Writing a Dockerfile Configure yum source cd /tmp...

Detailed description of the function of meta name="" content="

1. Grammar: <meta name="name" content...

The big role of HTML meta

There are two meta attributes: name and http-equiv...

How to connect to MySQL visualization tool Navicat

After installing Navicat The following error may ...

Analysis of different MySQL table sorting rules error

The following error is reported when MySQL joins ...

A brief introduction to MySQL InnoDB ReplicaSet

Table of contents 01 Introduction to InnoDB Repli...

Sample code for a large drop-down menu implemented in pure CSS

This is a large drop-down menu implemented purely...

MySQL 5.7 installation and configuration tutorial under CentOS7 (YUM)

Installation environment: CentOS7 64-bit, MySQL5....

Webpack file packaging error exception

Before webpack packaging, we must ensure that the...