使用集合属性绑定视图模型

Binding View-Models with collection properties

我的视图模型有一个唯一的 属性、currentProject,它本身有一个子 属性,它是一个字符串数组。当我将所有内容绑定到视图时,所有数据都会正确填充,包括字符串数组。当我编辑数据时,字符串数组没有更新。

我必须在这里做些什么才能使它成为双向绑定吗?我尝试了 two-way 命令,但没有任何区别。

我的视图模型如下所示:

export class Edit {
  currentProject;

  ...
}

CurrentProject 被设置为项目的实例 class:

export class Project {
  id = '';
  name = '';
  modifiedDate = '';
  createdBy = '';
  students = [];
}

我的编辑视图如下所示:

<template>
  <section>
    <h1>Edit ${currentProject.name}</h1>
    <form role="form" submit.delegate="save()">
      <label for="name">Project Name</label>
      <input type="text" maxlenth="100" id="name" value.bind="currentProject.name" />

      <h2>Students</h2>
      <div repeat.for="student of currentProject.students">
        <label for="name${index}">Student ${$index + 1}</label>
        <input type="text" maxlenth="100" id="name${$index}" value.bind="student" />
      </div>
      <button class="btn">Add Student</button>

      <button type="submit" class="btn btn-primary">Update project</button>
    </form>
  </section>
</template>

如有任何帮助,我们将不胜感激。我怀疑我遗漏了一些小细节。

谢谢, 安德鲁

看起来这里的问题是由于字符串(原始类型)的不可变性,您在输入字段中编辑的字符串与数组中的字符串之间没有引用,它只是两个不同的副本。

也就是说,您可以采用两种方法使其正常工作。最好的方法是为 students 设置对象数组,可能像这样:

[{name: 'Tomas Mann'}, {name: 'Alex Bloom'}]

然后 repeat.for 部分看起来像:

<div repeat.for="student of currentProject.students">
    <label for="name${index}">Student ${$index + 1}</label>
    <input type="text" maxlenth="100" id="name${$index}" value.bind="student.name" />
</div>

这种数据结构也比较灵活。例如,您可以添加其他学生信息,如年龄、分数等。您甚至可以将 students 数组作为学生对象 students: Student[] 等的数组

如果您仍然想使用简单字符串数组,那么您可以这样做:

<div repeat.for="student of currentProject.students">
    <label for="name${index}">Student ${$index + 1}</label>
    <input type="text" maxlenth="100" id="name${$index}" value.bind="$parent.currentProject.students[$index]" />
</div>