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>
相关推荐
We་ct几秒前
LeetCode 2. 两数相加:链表经典应用题详解
前端·算法·leetcode·链表·typescript
芝加哥兔兔养殖场4 分钟前
前端/iOS开发者必备工具软件合集
前端·ios
web打印社区4 分钟前
web-print-pdf:专为Web打印而生的专业解决方案
前端·javascript·vue.js·electron·html
糖糖TANG4 分钟前
学成在线 案例练习
前端·css
全栈前端老曹20 分钟前
【Redis】Redis 客户端连接与编程实践——Python/Java/Node.js 连接 Redis、实现计数器、缓存接口
前端·数据库·redis·python·缓存·全栈
午安~婉23 分钟前
构图跟拍相关
前端·javascript·拍照·虚拟列表
css趣多多28 分钟前
ref和reactive
前端
leo_23229 分钟前
前端&前端程序--SMP(软件制作平台)语言基础知识之六十
前端·开发工具·企业信息化·smp(软件制作平台)·应用系统
Charlie_lll30 分钟前
学习Three.js–柱状图
前端·3d·three.js
前端程序猿i34 分钟前
流式输出场景下的「双区域渲染」:让第三方 DOM 操作在 Vue 响应式更新中存活
前端·javascript·vue.js