You need to enable JavaScript to run this app. 如何在JavaScript函数中修改传入参数,实现Vue下拉选工具封装?
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript函数中修改传入参数,实现Vue下拉选工具封装?

问题原因
  1. 参数传递规则限制:JavaScript中字符串、数字等基础类型是按值传递,你调用工具函数时传入的form.value.selected_id、form.value.selected_name都是基础类型,传入函数的只是当前值的拷贝,函数内部修改formId、formName仅会修改局部变量,完全不会影响原form对象的属性。
  2. 原form定义存在问题:你给出的示例中form是仅配置了getter的只读计算属性,本身就不支持修改属性值,要存储可修改的表单数据应该使用ref或reactive定义。
修复方案

我们可以通过传入整个form响应式对象+属性名的方式解决传值问题,修改后的工具函数如下:

import { computed, type Ref, type WritableComputedRef } from 'vue'

// 下拉框通用工具函数
export const selectedDropdown = <T = Record<string, any>>(
  form: Ref<any> | WritableComputedRef<any>, // 传入整个form响应式对象
  formIdKey: string, // form中存储ID的属性名,例如'selected_id'
  formNameKey: string, // form中存储名称的属性名,例如'selected_name'
  optionIdKey = 'id', // 下拉选项对象的ID键名
  optionNameKey = 'name' // 下拉选项对象的名称键名
) => {
  return computed({
    get: () => {
      const id = form.value[formIdKey]
      return id ? {
        [optionIdKey]: id,
        [optionNameKey]: form.value[formNameKey]
      } as T : null
    },
    set: (val: T | null) => {
      form.value[formIdKey] = val ? val[optionIdKey] : ''
      form.value[formNameKey] = val ? val[optionNameKey] : ''
    }
  })
}

首先你需要把原来的form修改为可写的响应式对象:

// 替换原来的只读computed定义
const form = ref({
  selected_id: '',
  selected_name: '',
  other_value: ''
})

调用工具函数的方式如下:

const selectedContact = selectedDropdown(
  form,
  'selected_id',
  'selected_name'
)

可选更灵活方案

如果你不想把整个form对象传入工具函数,可以用传读写函数的方式,适配任意嵌套结构的属性:

import { computed, type ComputedRef } from 'vue'

export const selectedDropdown = <T = Record<string, any>>(
  getId: () => string | number,
  setId: (val: string | number) => void,
  getName: () => string,
  setName: (val: string) => void,
  optionIdKey = 'id',
  optionNameKey = 'name'
): ComputedRef<T | null> => {
  return computed({
    get: () => getId() ? { [optionIdKey]: getId(), [optionNameKey]: getName() } as T : null,
    set: (val) => {
      setId(val ? val[optionIdKey] : '')
      setName(val ? val[optionNameKey] : '')
    }
  })
}

// 调用示例
const selectedContact = selectedDropdown(
  () => form.value.selected_id,
  (v) => form.value.selected_id = v,
  () => form.value.selected_name,
  (v) => form.value.selected_name = v
)

内容的提问来源于stack exchange,提问作者Ihsan Fajar Ramadhan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 18:48:03