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>
相关推荐
无羡仙18 分钟前
替代 Object.freeze 的精准只读模式
前端·javascript
web前端12327 分钟前
Java客户端开发指南 - 与Web开发对比分析
前端
龙在天28 分钟前
前端 9大 设计模式
前端
搞个锤子哟29 分钟前
网站页面放大缩小带来的问题
前端
hj5914_前端新手29 分钟前
React 基础 - useState、useContext/createContext
前端·react.js
半花32 分钟前
【Vue】defineProps、defineEmits 和 defineExpose
前端·vue.js
霍格沃兹_测试38 分钟前
软件测试 | 测试开发 | H5页面多端兼容测试与监控
前端
toooooop81 小时前
本地开发环境webScoket调试,保存html即用
前端·css·websocket
山有木兮木有枝_1 小时前
手动封装移动端下拉刷新组件的设计与实现
前端
阳光阴郁大boy1 小时前
大学信息查询平台:一个现代化的React教育项目
前端·react.js·前端框架