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>
相关推荐
沐言人生7 小时前
自媒体人的效率神器!监控、采集、下载、发布,这个免费开源工具全拿下!
前端·vue.js·后端
怕浪猫9 小时前
NVIDIA 全产品谱系与演进
javascript·面试·github
excel9 小时前
为什么 super 中能接收到 resolve 和 reject?
前端
Flynt11 小时前
AI 生成的界面,能放心点吗?我把 Google A2UI 的三层防线拆开测了一遍
前端·google·agent
前端混子12 小时前
我用 AI 做了个「禾月小历」,一套代码跑微信小程序和 H5
前端
Flynn Liang12 小时前
AI Agent Redis 生产踩坑实录:13 类故障的根因、复现与调优
数据库·人工智能·redis·缓存·ai agent·故障分析
IT_陈寒12 小时前
Java实战技巧总结:当你的finally块没有执行时会发生什么?
前端·人工智能·后端
小帅不太帅12 小时前
一年一次黑五,为了买软件真省钱,我做了个开源小站
前端·人工智能·github
JavaGuide14 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang021715 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html