Vue - 将对象的值绑定到复选框值

时间:2017-10-26 11:33:37

标签: javascript vue.js

我想将每个项目的值放入数组<ul class="list-group no-bullets"> <li class="list-group-item" v-for="item in parks"> <label><input type="checkbox" value="item" v-model="selectedParks"/> {{item.name}}</label> </li> </ul> <span>Checked: {{selectedParks}}</span> 。问题是,值始终设置为字符串“item”,而不是实际项目的值(它是Park对象)。

代码:

item

我知道实际的{{item.name}}绑定正确,因为 static void Main(string[] args) { List<Obvious> list = new List<Obvious>(); for (int i = 0; i < 100; i++) { list.Add(new Obvious(i.ToString(), i)); } string name = list[30].name; switch (name) { case "9": list.OrderBy(o => o.perc) .ThenByDescending(o => o.name); break; default: list.OrderByDescending(o => o.name) .ThenBy(o => o.perc); break; } } public class Obvious { public string name { get; set; } public int perc { get; set; } public Obvious(string _name, int _perc) { this.name = _name; this.perc = _perc; } } 显示正确的值。

文档(绑定到同一数组的多个复选框):https://vuejs.org/v2/guide/forms.html

1 个答案:

答案 0 :(得分:7)

因为value被评估为字符串,所以需要使用v-bind将其设置为对象:

<input type="checkbox" v-bind:value="item" v-model="selectedParks"/>

或结肠速记:

<input type="checkbox" :value="item" v-model="selectedParks"/>