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

Vue3如何合并多个含get/set的computed以精简代码?

精简Vue3中重复的双向绑定Computed代码

当然可以,你可以通过工厂函数+字段列表的方式批量生成这些逻辑重复的computed,彻底消除冗余代码,具体实现如下:

修改后的完整代码

<template>
  <input v-model="formFields.equipmentCode" size="50" style="width: 200px" />
  <input v-model="formFields.equipmentName" size="50" />
  <input v-model="formFields.classification" size="50" />
</template>

<script setup>
import { ref, computed } from 'vue';

const itemData = ref({}); // 从服务端获取的数据
const newData = ref({});
const props = defineProps({
  id: {}
});

// 1. 定义需要处理的字段列表
const fieldNames = ['equipmentCode', 'equipmentName', 'classification'];

// 2. 封装生成computed的工厂函数
const createFieldComputed = (field) => {
  return computed({
    get: () => {
      return props.id ? itemData.value[field] : newData.value[field];
    },
    set: (newValue) => {
      props.id ? (itemData.value[field] = newValue) : (newData.value[field] = newValue);
    }
  });
};

// 3. 批量生成所有字段的computed并整合
const formFields = {};
fieldNames.forEach(field => {
  formFields[field] = createFieldComputed(field);
});
</script>

代码说明

  • 字段列表:把所有需要双向绑定的字段名统一维护在数组中,后续新增字段只需往数组里追加,无需重复写computed逻辑。
  • 工厂函数:将重复的get/set逻辑封装成函数,通过传入不同字段名动态生成对应computed,彻底复用逻辑。
  • 批量整合:通过循环字段列表,调用工厂函数生成每个字段的computed,最终整合到formFields对象中,模板直接通过formFields.字段名绑定即可。

如果想保持模板里原有的独立变量名(不用formFields.xxx),可以直接解构暴露:

// 解构为独立变量,模板可直接用equipmentCode这类变量
const { equipmentCode, equipmentName, classification } = formFields;

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 21:58:10