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>
相关推荐
Aric_Jones14 分钟前
JavaScript 从入门到精通:完整语法指南
开发语言·javascript·ecmascript
岱宗夫up20 分钟前
FastAPI入门(上篇):快速构建高性能Python Web API
开发语言·前端·python·fastapi
紫陌涵光1 小时前
112. 路径总和
java·前端·算法
漠月瑾-西安1 小时前
CVE-2025-55182漏洞解析:你的React项目安全吗?
前端·安全·react.js
No丶slovenly1 小时前
flutter笔记-输入框
前端·笔记·flutter
国产化创客2 小时前
ESP32+Web实现智能气象站
前端·物联网·智能家居·智能硬件
学到头秃的suhian2 小时前
Redis消息队列
数据库·redis·缓存
2401_848009722 小时前
Redis进阶学习
数据库·redis·学习·缓存
coderYYY3 小时前
VSCode终端启动报错
前端·ide·vscode·npm·编辑器
西门吹-禅3 小时前
文本搜索node js--meilisearch
开发语言·javascript·ecmascript