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>
相关推荐
mCell14 分钟前
【短文】不是最强,是最适合
前端·aigc·deepseek
余瑜鱼鱼鱼1 小时前
HTML常用标签总结
前端·html
Jave21081 小时前
Vue 中 mixins 混合开发的主要使用场景有哪些?
前端·vue.js
徐同保1 小时前
openclaw安装
前端
JEECG低代码平台2 小时前
JeecgBoot低代码平台 Ant Design Vue 4.x 升级避坑指南
前端·vue.js·低代码
yashuk2 小时前
Go-Gin Web 框架完整教程
前端·golang·gin
唐叔在学习2 小时前
e.preventDefault()到底怎么用?
前端·javascript
北寻北爱2 小时前
面试题-vue篇
前端·vue.js
XPoet2 小时前
AI 编程工程化:Skill——给你的 AI 员工装上技能包
前端·后端·ai编程
JEECG低代码平台2 小时前
JeecgBoot低代码平台 Qiankun 微前端集成指南:主应用配置全流程
前端·低代码