場景:在列表中,有這么一個屬性,需要通過同行的其他屬性,進行復雜的計算,才能得出,如果我們用方法,然后傳參,得到這個屬性,那么每次更改列表后,每行都會重新計算,耗費性能。如果我們有一個可緩存的方法,在參數沒有改變的時候,返回之前得到的緩存結果。只有在參數改變的時候,重新計算。
我們可以構建一個工具函數,將計算函數作為參數,會返回一個帶緩存的函數。如下 useComputed.js:
// 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;};
}
使用:
<template> {{ computedPrice(row) }} </template><script setup>import { useComputed } from "./useComputed.js";function totalPrice(row) {return row.price * row.count;}const computedPrice = useComputed(totalPrice);
</script>