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

How to change apt-get source in Ubuntu 18.04

When using apt-get to install, it will be very sl...

The easiest way to reset mysql root password

My mysql version is MYSQL V5.7.9, please use the ...

Detailed explanation of using grep command in Linux

Linux grep command The Linux grep command is used...

MySql common query command operation list

MYSQL commonly used query commands: mysql> sel...

JS realizes the front-end paging effect

This article example shares the specific code of ...

MySQL 8.0.13 installation and configuration method graphic tutorial under win10

I would like to share the installation and config...

Use the CSS border-radius property to set the arc

Phenomenon: Change the div into a circle, ellipse...

Detailed explanation of the basic use of react-navigation6.x routing library

Table of contents react-native project initializa...

The connection between JavaScript and TypeScript

Table of contents 1. What is JavaScript? 2. What ...

Will css loading cause blocking?

Maybe everyone knows that js execution will block...

A brief analysis of the use of the HTML webpack plugin

Using the html-webpack-plugin plug-in to start th...

10 Underused or Misunderstood HTML Tags

Here are 10 HTML tags that are underused or misun...

Automatic backup of MySQL database using shell script

Automatic backup of MySQL database using shell sc...

How to set up cross-domain access in IIS web.config

Requirement: The page needs to display an image, ...