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>
相关推荐
苦夏木禾几秒前
css实现表格中最后一列固定
前端·javascript·css
LuHang11 分钟前
WebSocket服务封装实践:从连接管理到业务功能集成
前端·websocket
九十一12 分钟前
vue2中$set的原理
前端
闲不住的李先森18 分钟前
深入解析 Cursor 规则:为团队打造统一的 AI 编程规范
前端·ai编程·cursor
FlowGram32 分钟前
FlowGram 官网建设
前端
晚枫~38 分钟前
零基础快速上手Playwright自动化测试
javascript·python·测试工具·c#·自动化
~无忧花开~38 分钟前
JavaScript学习笔记(二十八):JavaScript性能优化全攻略
开发语言·前端·javascript·笔记·学习·性能优化·js
BumBle39 分钟前
基于UniApp实现DeepSeek AI对话:流式数据传输与实时交互技术解析
前端·uni-app
九十一41 分钟前
vue3事件总线与emit
前端·vue.js
岁月向前1 小时前
不同的协议和场景防丢包方案
前端