vue封装带有缓存的函数
vue中有时候列表上的某些参数需要经过复杂且耗时的计算时,会造成性能问题,原因是列表上的某一行数据变化后,整个组件的reder函数都会重新运行,那么每行都会重新进行复杂的运算。
计算属性不支持传参,才有的下文。
解决方案:封装带有缓存功能的函数。
// Vue3示例
<script setup lang="ts">
import { computed, reactive } from 'vue';
const cacheMap = new Map()
function getCountPlant(fn) {
return function (v) {
if (cacheMap.has(v)) {
return cacheMap.get(v)
}
const cacheData = computed(() => fn(v))
cacheMap.set(v, cacheData.value)
console.log(v, '---------', cacheData.value);
return cacheData.value
}
}
function getCount(v) {
return v * 10 + (v + 1) * (v - 1)
}
const newGetCount = getCountPlant(getCount)
const testData = reactive({
value: [
{
id: 1,
title: '第一个标题',
value: 1,
},
{
id: 2,
title: '第一个标题',
value: 2,
},
{
id: 3,
title: '第一个标题',
value: 3,
},
] })
const edit = () => {
const r = ~~(Math.random() * 3)
const v = ~~(Math.random() * 100) + 1
testData.value[r].value = v
const r2 = ~~(Math.random() * 3)
const v2 = ~~(Math.random() * 100) + 1
testData.value[r2].value = v2
}
</script>
<template>
<el-button @click="edit">click</el-button>
<div v-for="item in testData.value" :key="item.id">{{ item.title }}-- {{ newGetCount(item.value) }}</div>
</template>
<style scoped lang="scss"></style>