SoFunction
Updated on 2025-03-04

How to use Vue cache function cleverly

Cache Functions 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 = (null);
    return (function cachedFn (str) {
      var hit = cache[str];
      return hit || (cache[str] = fn(str))
    })
  }
  

There is a common scenario for the above function, such as an array, and the first letter of each element needs to be converted to capitalization.

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

Common solutions

// Define a capitalize functionfunction capitalize (str) {
    return (0).toUpperCase() + (1)
 };
  
 const capitalizeArray = (capitalize);

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

Renovation as follows

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

When a duplicate string is encountered, the cached result will be returned directly. Think about capitalize is a very time-consuming task, with more than a little performance optimization.

Reform vue cache function

The above example is a pure function of cache synchronization tasks. There is such a scenario in business development, input box search. When the input box triggers the input event, we will call the interface to return the query result. For example, I entered the Nuggets keyword and returned the result, and then entered the Nuggets NBA and returned the result. At this time, I deleted the NBA and queryed the Nuggets again. In fact, we have checked this result before. If it is cached, just directly cache it, and there is no need to call the interface.

We implement a memorandum of cached asynchronous pure functions based on cached

const cachedAsync = function(fn) {
    const cache = (null);
    return async str => {
        const hit = cache[str];
        if (hit) {
            return hit;
        }
        // Only successful promises are cached, and re-requested if failed        return (cache[str] = await fn(str));
    };
};

Use scenarios

const cachedAsyncQueryPrdList = cachedAsync(prdNo => {
    // The following is a requested 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="" :value="">
    </el-select>
</template>
<script>
export default {
    data() {
        prdNo: '',
        prdList: [],
    },
    methods: {
        async handleQueryPrdList() {
            const { data } = await cachedAsyncQueryPrdList();
             = data;
        }
    }
}
</script>

The above implementation is that when entering the same keyword, if the previous request was successful, the cache will be directly pulled up and the request will not be initiated to the server again. Because our memo will only cache successful promises.

optimization

For the above scenario, although the compositionEnd and compositionStart events are used in the underlying el-input layer to make a layer of anti-shake, the input event will be triggered only if the text is actually entered on the screen. But this is not enough. If the user inputs quickly, the requests will be sent several times in a second, which will increase the burden on the server. Therefore, this is generally used with anti-shake function.

Anti-shake function

const debounce = (fn, ms = 300) => {
    let timeoutId;
    return function(...args) {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => (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="" :value="">
    </el-select>
</template>
<script>
const noop = () => {};
export default {
    data() {
        prdNo: '',
        prdList: [],
        debounceQueryPrdListFn: noop,
    },
    created() {
         = debounce();
    },
    methods: {
        async handleQueryPrdList() {
            const { data } = await cachedAsyncQueryPrdList();
             = data;
        }
    }
}
</script>

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

This implementation has been used stably in the production environment and everyone can eat it with confidence.

Summarize

This is the end of this article about how to use Vue cache functions ingeniously. For more related content on using Vue cache functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!