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 小时前
Vuetify:构建优雅Vue应用的Material Design组件库
前端·javascript·vue.js
wangbing11251 小时前
界面规范11-对话框
javascript·vue.js·elementui
shan&cen1 小时前
Day02 集合 | 30. 串联所有单词的子串、146. LRU 缓存、811. 子域名访问计数
java·数据结构·算法·缓存
roman_日积跬步-终至千里1 小时前
【系统架构设计(25)】Web应用服务器与现代架构
前端·架构·系统架构
yshhuang1 小时前
在Windows上搭建开发环境
前端·后端
littleplayer1 小时前
Redux在iOS中的使用
前端
跟橙姐学代码1 小时前
Python里的“管家婆”:带你玩转os库的所有神操作
前端·python·ipython
jingling5551 小时前
uniapp | 快速上手ThorUI组件
前端·笔记·前端框架·uni-app
UrbanJazzerati1 小时前
可拖拽的进度条组件实战:实现思路与Demo
前端·面试