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>
相关推荐
西岭千秋雪_1 小时前
Redis性能优化
数据库·redis·笔记·学习·缓存·性能优化
abigale031 小时前
webpack+vite前端构建工具 -11实战中的配置技巧
前端·webpack·node.js
en-route2 小时前
HTTP 缓存
网络协议·http·缓存
专注API从业者2 小时前
构建淘宝评论监控系统:API 接口开发与实时数据采集教程
大数据·前端·数据库·oracle
Joker`s smile2 小时前
Chrome安装老版本、不同版本,自制便携版本用于前端调试
前端·chrome
weixin_416639972 小时前
爬虫工程师Chrome开发者工具简单介绍
前端·chrome·爬虫
我是如子啊2 小时前
【解决“此扩展可能损坏”】Edge浏览器(chrome系列通杀))扩展损坏?一招保留数据快速修复
前端·chrome·edge
灵性花火2 小时前
Qt的前端和后端过于耦合(0/7)
开发语言·前端·qt
孤水寒月6 小时前
基于HTML的悬窗可拖动记事本
前端·css·html
祝余呀6 小时前
html初学者第一天
前端·html