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>
相关推荐
琹箐几秒前
今天吃什么干什么随机生成
javascript·css·css3
6Hzlia几秒前
Hot 100 刷题计划】 LeetCode 146. LRU 缓存 | C++ 哈希表+双向链表
c++·leetcode·缓存
鹏程十八少1 分钟前
10. 2026金三银四 Android 组件化 & ARouter 面试杀手锏:33 道高频题 + 答案 + 流程图 + 源码,资深工程师必刷
前端·后端·面试
yqcoder1 分钟前
CSS 布局双雄:浮动 (Float) vs 绝对定位 (Absolute) 深度解析
前端·css
Controller-Inversion4 分钟前
146. LRU 缓存
缓存
朝阳397 分钟前
react【实战】首页 -- 白天/黑夜主题切换(含组件封装)
前端·react.js·前端框架
卷Java7 分钟前
ReAct范式实战:让Agent学会边想边做
javascript·react.js·大模型·llm·ecmascript·multi-agent
吴声子夜歌8 分钟前
Vue3——UI组件库Element Plus(二)
javascript·vue.js·ui·elementplus
无心使然云中漫步12 分钟前
Openlayers调用ArcGis地图服务之五 —— 要素识别(/identify)
前端·arcgis·vue·数据可视化
yuzhiboyouye20 分钟前
java redis(缓存)
java·redis·缓存