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>
相关推荐
徐小夕1 小时前
被CRUD拖垮的第5年,我用Cursor 一周"复仇":pxcharts-vue开源,一个全栈老兵的AI编程账本
前端·vue.js·github
Wect3 小时前
LeetCode 39. 组合总和:DFS回溯解法详解
前端·算法·typescript
Wect3 小时前
LeetCode 46. 全排列:深度解析+代码拆解
前端·算法·typescript
IT_陈寒3 小时前
Vite 凭什么比 Webpack 快50%?揭秘闪电构建背后的黑科技
前端·人工智能·后端
颜酱3 小时前
Dijkstra 算法:从 BFS 到带权最短路径
javascript·后端·算法
hi大雄3 小时前
我的 2025 —— 名为《开始的勇气》🌱
前端·年终总结
从文处安4 小时前
「前端何去何从」一直写 Vue ,为何要在 AI 时代去学 React?
前端·react.js
aircrushin4 小时前
OpenClaw“养龙虾”现象的社会技术学分析
前端·后端
明君879974 小时前
#Flutter 的官方Skills技能库
前端·flutter
yuki_uix4 小时前
重新认识 React Hooks:从会用到理解设计
前端·react.js