How to use Vue cache function

How to use Vue cache function

Cache function in vue2

There is such a cache function in the vue2 version

  /**
   * Create a cached version of a pure function.
   */
  function cached (fn) {
    var cache = Object.create(null);
    return (function cachedFn (str) {
      var hit = cache[str];
      return hit || (cache[str] = fn(str))
    })
  }
  

The above function has a common scenario, for example, there is an array and the first letter of each element needs to be converted to uppercase.

const array = ['abc', 'ed', 'abc', 'acd', 'ed', 'fkg', ...];

Common solutions

// Define a capitalize function function capitalize (str) {
    return str.charAt(0).toUpperCase() + str.slice(1)
 };
  
 const capitalizeArray = array.map(capitalize);

If we are careful, we will find that there are many repeated elements in the array. They return the same results. In fact, there is no need to repeat the calculation to execute capitalize. Moreover, capitalize is a PURE function. At this time, we can use the cached function above to make a memo.

The transformation is as follows

function capitalize(str) {
    return str.charAt(0).toUpperCase() + str.slice(1)
 };
  
const capitalizeArray = array.map(cached(capitalize));

When a duplicate string is encountered, the cached result will be returned directly. Consider that capitalization is a very time-consuming task, and performance optimization requires more than a little bit.

Transform vue cache function

The above example is a pure function of the cache synchronization task. In business development, there is such a scenario: input box search. When the input box triggers an input event, we will call the interface to return the query results. For example, I entered the keyword Nuggets and the result was returned, and then I entered Nuggets NBA and the result was returned. At this time, I deleted NBA and searched for Nuggets again. In fact, we have checked this result before. If it is cached, we can directly pull the cache without calling the interface again.

We implement a memo for caching asynchronous pure functions based on cache

const cachedAsync = function(fn) {
    const cache = Object.create(null);
    return async str => {
        const hit = cache[str];
        if (hit) {
            return hit;
        }
        // Only cache successful Promises, and directly re-request return if failed (cache[str] = await fn(str));
    };
};

Usage scenarios

const cachedAsyncQueryPrdList = cachedAsync(prdNo => {
    // The following is a request operation, returning a promise
    return queryPrdList({
        prdNo
    });
}); 

<template>
    <el-input v-model="prdNo" placeholder="Please enter the product code" @input="handleQueryPrdList" />
    <el-select>
        <el-option v-for="item in prdList" :label="item.label" :value="item.value">
    </el-select>
</template>
<script>
export default {
    data() {
        prdNo: '',
        prdList: [],
    },
    methods: {
        async handleQueryPrdList() {
            const { data } = await cachedAsyncQueryPrdList(this.prdNo);
            this.prdList = data;
        }
    }
}
</script>

The above implementation means that when the same keyword is entered, if the previous request was successful, the cache is directly pulled up without making a new request to the server. Because our memo will only cache successful promises.

optimization

For the above scenario, although the el-input underlying layer has used compositionEnd and compositionStart events to do a layer of anti-shake, the input event will only be triggered when the text is actually entered on the screen. But this is not enough. If the user types very quickly, several requests may be sent per second, increasing the burden on the server. Therefore, this type of function is generally used in conjunction with the anti-shake function.

Anti-shake function

const debounce = (fn, ms = 300) => {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => fn.apply(this, args), ms);
    };
};

Then use it with our cachedAsync

const cachedAsyncQueryPrdList = cachedAsync(prdNo => {
    // The following is an ajax request operation, returning a promise
    return queryPrdList({
        prdNo
    });
}); 

<template>
    <el-input v-model="prdNo" placeholder="Please enter the product code" @input="debounceQueryPrdListFn" />
    <el-select>
        <el-option v-for="item in prdList" :label="item.label" :value="item.value">
    </el-select>
</template>
<script>
const noop = () => {};
export default {
    data() {
        prdNo: '',
        prdList: [],
        debounceQueryPrdListFn: noop,
    },
    created() {
        this.debounceQueryPrdListFn = debounce(this.handleQueryPrdList);
    },
    methods: {
        async handleQueryPrdList() {
            const { data } = await cachedAsyncQueryPrdList(this.prdNo);
            this.prdList = data;
        }
    }
}
</script>

FBI WARNING: >>> cachedAsync function, only applicable to PURE functions.

This implementation has been used stably in the production environment, so you can use it with confidence.

Summarize

This is the end of this article on how to use Vue cache functions. For more information on how to use Vue cache functions, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you 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 component caching in Vue
  • About Vue's component information caching problem
  • Detailed explanation of page caching in Vue

<<:  Briefly describe how to install Tomcat image and deploy web project in Docker

>>:  Solve the problem of combining AND and OR in MySQL

Recommend

Advantages of INSERT INTO SET in MySQL

Insert data into mysql database. Previously commo...

How to enter directory/folder in Linux without using CD command

As we all know, without the cd command, we cannot...

How to install Linux flash

How to install flash in Linux 1. Visit the flash ...

CSS scroll-snap scroll event stop and element position detection implementation

1. Scroll Snap is a must-have skill for front-end...

8 JS reduce usage examples and reduce operation methods

reduce method is an array iteration method. Unlik...

Detailed analysis of mysql MDL metadata lock

Preface: When you execute a SQL statement in MySQ...

A brief analysis of React Native startReactApplication method

In this article, we sorted out the startup proces...

MySQL Quick Data Comparison Techniques

In MySQL operation and maintenance, a R&D col...

MySQL 8.0.15 winx64 installation and configuration method graphic tutorial

This article shares the installation and configur...

js to achieve the pop-up effect

This article example shares the specific code of ...

Detailed explanation of MySQL slow log query

Slow log query function The main function of slow...

VUE+Canvas implements the game of God of Wealth receiving ingots

Welcome to the previous canvas game series: 《VUE ...

Detailed explanation of making shooting games with CocosCreator

Table of contents Scene Setting Game Resources Tu...