Skip to content

v-decorator 数组索引解析 #1789

@EmiyaYang

Description

@EmiyaYang
  • I have searched the issues of this repository and believe that this is not a duplicate.

Version

1.4.11

Environment

vue 2.5

Reproduction link

Edit on CodeSandbox

Steps to reproduce

运行沙盒, 进入 /src/component 查看 HelloWorld.vue 源码

What is expected?

// 该条语句能将 decoratorId 为 'a.0' 的 form-item 设置为 2.
form.setFieldsValue({ 'a': [2] });

What is actually happening?

不能正确赋值

Additional comments

我明白这可能不算 BUG, decoratorId 的路径都是被当成对象的键处理的. 兼容数组索引可能存在二义性. 但我提上来还是想问问官方能不能抹平二者的差异. 我个人写了一个函数用于生成键位路径.

export function flattenObj(value, depth = Infinity, keys = []) {
  if (typeof value !== 'object' || value == null || keys.length >= depth) {
    if (!keys || !keys.length) return value;

    const key = keys.join('.');

    return { [key]: value };
  }

  let res = {};

  Object.keys(value).forEach(key => {
    const val = value[key];

    res = { ...res, ...flattenObj(val, depth, [...keys, key]) };
  });

  return res;
}

不知大家有没有更推荐的方式?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions