You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue.js:基于Map与Ref的计算属性优化(避免forEach循环)

优化方案:用函数式数组操作替代forEach循环

你可以利用数组的链式操作(Array.from + filter + map)替代手动的forEach循环,代码更简洁且符合声明式编程风格,同时避免手动维护结果数组:

const selectedData = computed(() => {
  // 把选中的source guid转成Set,提升查找性能(数组includes是O(n),Set.has是O(1))
  const selectedSourceSet = new Set(selectedSourceGuids.value)
  const targetTopic = selectedTopic.value

  return Array.from(data.value.sources.entries())
    // 筛选出符合两个条件的项:guid在选中列表里,且该source有对应topic的数据
    .filter(([key, source]) => selectedSourceSet.has(key) && source.data.has(targetTopic))
    // 生成对应的DataSerie实例
    .map(([key, source]) => {
      // 因为前面已经用has判断过,这里可以安全断言数据存在
      const topicData = source.data.get(targetTopic)!
      return new DataSerie(topicData, key, key)
    })
})

优化点说明:

  1. 替换forEach为链式操作:用Array.from把Map的键值对转成数组,之后通过filter筛选符合条件的项,再用map生成目标对象,逻辑更清晰,无需手动push元素到结果数组。
  2. 性能优化:将selectedSourceGuids转成Set,把查找操作的时间复杂度从O(n)降到O(1),当选中的guid数量较多时提升明显。
  3. 提前缓存变量:把selectedTopic.value缓存到targetTopic变量,避免在链式操作中多次读取ref的value属性,减少不必要的属性访问。

如果你的场景中selectedSourceGuids的长度一直很小,也可以跳过转Set的步骤,直接用selectedSourceGuids.value.includes(key),但转Set的方案在性能上更有优势。

内容的提问来源于stack exchange,提问作者Reza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 06:50:18