使用 Ractive 在多个 select 中设置预 select 值

Setting preselected values in multiple select with Ractive

我在 Ractive 中渲染了一个 select multiple,其中包含所有可能选项的计算列表,效果很好。但是我找不到预选值的正确方法。

到目前为止我有类似的东西:

data = [{
  type: "Person",
  Name: "John",
  worksFor: [
    "1",
    "2"
]},{
   type: "department",
   id: "1",
   Name: "Sales"
},{
   type: "department",
   id: "2",
   Name: "Marketing"
},{
   type: "department",
   id: "3",
   Name: "Accounting"
}]
new Ractive({
    el: '#list',
    template: DataTpl,
    data: {myData: data},
    computed: {
        DepartmentList () {
            //some code
            return list_of_all_Departments;
        },
        PersonsList () {
            //some Code
            return list_of_persons
        });

所以在我的模板中我尝试了

{{#PersonsList}}
<select multiple>
    {{#DepartmentList}}
        <option value="{{id}}" 
            {{#if _.includes(PersonsList.worksFor, id)}} selected{{/if}}>{{Name}}
        </option>
    {{/DepartmentList}}
</select>
{{/PersonsList}}

但这只是给了我一个failed to compute。有谁知道如何获得这些预选?

您必须给 select 一个值并将该值设置为默认值

这是Ractive偏离标准的地方之一。您需要在 <select> 上放置一个 value 属性。 selected <option>value 变成了 <select>value。您将从 <select> 获得的数据类型取决于它是否为多个。如果它是单个-select,您将获得单个值。如果是多个-select,你会得到一个数组。

设置预 selected 值正好相反。将数据中的值分配给 <select>value,假设这些值存在于 <option> 中,它们将被 selected。不需要模板修改。

Ractive.DEBUG = false;

var data = [{
  type: "Person",
  Name: "John",
  worksFor: [
    "1",
    "2"
  ]
}, {
  type: "department",
  id: "1",
  Name: "Sales"
}, {
  type: "department",
  id: "2",
  Name: "Marketing"
}, {
  type: "department",
  id: "3",
  Name: "Accounting"
}];

new Ractive({
  el: '#list',
  template: '#template',
  data: {
    selectedDepartments: [],
    myData: data
  },
  computed: {
    DepartmentList() {
      return this.get('myData').filter(v => v.type === 'department');
    },
    PersonsList() {
      return this.get('myData').filter(v => v.type === 'Person');
    }
  }
});
<script src="https://unpkg.com/ractive@0.8.11/ractive.min.js"></script>
<div id="list"></div>

<script type="template/ractive" id="template">
  {{#PersonsList}}
    {{ Name }}
  
    <select multiple value="{{ worksFor }}">
      {{#DepartmentList}}
        <option value="{{id}}">{{Name}}</option>
      {{/DepartmentList}}
    </select>
  {{/PersonsList}}
</script>