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>
相关推荐
Levi_J14 分钟前
Vue2 升级 Vue3 项目实战
前端
前端拷贝猿15 分钟前
扫码领券功能需求分析
前端
前端拷贝猿19 分钟前
设备活动弹窗功能需求分析
前端
飞天狗11124 分钟前
零基础JavaWeb入门——第五课第一小节:九大内置对象 · 第1个:request(请求对象)
java·开发语言·前端·后端·servlet
a151084169334 分钟前
记一次大模型探索
java·服务器·前端
石山代码35 分钟前
变量与解构
开发语言·前端·javascript
888CC++1 小时前
箭头函数(ES6)
前端·javascript·es6
qq_419854051 小时前
css filter
前端·javascript·css
Agatha方艺璇1 小时前
VUE复习笔记
前端·vue.js
大家的林语冰2 小时前
npm 不忍了,正式上线“阶段式发布“的新功能,进一步对抗频繁的供应链攻击!
前端·javascript·node.js