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

Vue实现v-model绑定动态JSON节点(不存在则自动创建)

实现Vue中v-model绑定动态JSON节点并自动创建层级

要实现v-model绑定由字符串指定的JSON对象动态节点,且自动创建不存在的嵌套层级,可以通过计算属性结合路径解析来完成,核心是实现动态路径的取值和赋值逻辑:

核心逻辑

  1. 将路径字符串(如Response.ParentObject.ChildVal)拆分为层级节点数组
  2. 取值时(get):逐层遍历节点,返回对应值或默认值
  3. 赋值时(set):逐层检查节点是否存在,不存在则创建空对象,最终设置目标值

完整代码示例

假设组件中根对象为formData,配置参数responseNode为目标路径:

<template>
  <v-text-field v-model="dynamicValue"></v-text-field>
</template>

<script>
export default {
  data() {
    return {
      formData: {},
      responseNode: 'Response.ParentObject.ChildVal'
    }
  },
  computed: {
    dynamicValue: {
      get() {
        let current = this.formData
        const segments = this.responseNode.split('.')
        for (const seg of segments) {
          if (!current || !(seg in current)) return ''
          current = current[seg]
        }
        return current
      },
      set(newVal) {
        let current = this.formData
        const segments = this.responseNode.split('.')
        // 遍历创建中间层级
        for (let i = 0; i < segments.length - 1; i++) {
          const seg = segments[i]
          if (!current[seg] || typeof current[seg] !== 'object') {
            current[seg] = {}
          }
          current = current[seg]
        }
        // 设置最终节点值
        current[segments.at(-1)] = newVal
      }
    }
  }
}
</script>

补充说明

  • 若responseNode包含根对象名(如formData.Response.ParentObject.ChildVal),可在拆分路径后先提取根对象:
    const segments = this.responseNode.split('.')
    const rootName = segments.shift()
    let current = this[rootName]
    
  • 输入值后,formData会自动生成预期的嵌套结构:
    formData: {
      Response: {
        ParentObject: {
          ChildVal: 10 // 输入的具体值
        }
      }
    }
    
  • 可根据需求调整默认返回值(如get方法返回0),或扩展逻辑支持数组类型节点

内容的提问来源于stack exchange,提问作者Binesh Nambiar C

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:55:21