vue3 中可缓存的方法

场景:在列表中,有这么一个属性,需要通过同行的其他属性,进行复杂的计算,才能得出,如果我们用方法,然后传参,得到这个属性,那么每次更改列表后,每行都会重新计算,耗费性能。如果我们有一个可缓存的方法,在参数没有改变的时候,返回之前得到的缓存结果。只有在参数改变的时候,重新计算。

我们可以构建一个工具函数,将计算函数作为参数,会返回一个带缓存的函数。如下 useComputed.js:

javascript 复制代码
// useComputed.js
import { computed } from "vue";

export function useComputed(fn) {
  const cache = new Map();

  function getCache(args) {
    return cache.get(JSON.stringify(args));
  }

  return function (...args) {
    const cacheResult = getCache(args);
    if (cacheResult) {
      return cacheResult;
    }
    const result = computed(() => fn(...args));
    cache.set(JSON.stringify(args), result);
    return result;
  };
}

使用:

html 复制代码
<template> {{ computedPrice(row) }} </template>

<script setup>
  import { useComputed } from "./useComputed.js";

  function totalPrice(row) {
    return row.price * row.count;
  }

  const computedPrice = useComputed(totalPrice);
</script>
相关推荐
挖稀泥的工人几秒前
AI 打字跟随优化
前端·javascript·vue.js
jiayong231 分钟前
第 11 课:把筛选条件同步到 URL
开发语言·前端·javascript
Mintopia5 分钟前
性能优化的错觉:你优化的,可能根本不是瓶颈
前端
Mintopia6 分钟前
一次讲清"慢"的本质:CPU、IO、网络到底谁在拖后腿
javascript
05Nuyoah7 分钟前
第一阶段:HTML的笔记
前端·笔记·html
DazedMen7 分钟前
前端自定义接口返回,想咋玩就咋玩
前端·vue·接口拦截
GISer_Jing8 分钟前
前端图片·动图·动画 技术完全指南
前端·面试·动画
Mapmost8 分钟前
从拉到夯,一张矢量地图的五个段位
前端