你应该做的第一件事是价值观和v-模型绑定到你的复选框:
<input type="checkbox" :id="subregion[0].subregion" v-model="subregionCheck" :value="subregion[0].subregion">
<input type="checkbox" :id="country.name" v-model="countryCheck" :value="country.name">
而在你的数据添加subregionCheck和countryCheck的数组:
data: {
subregions: null,
countries: null,
query: '',
countryList: [],
subregionCheck:[],
countryCheck: []
},
这些阵列作为服务我们复选框的标记:如果它们包含单个复选框的值,它将被检查。在开始时他们都是空的。
在接下来的步骤中,我们应该为子区域创建一个侦听器复选框和一个用于检查该子区域的所有国家复选框的函数。让我们先添加一个点击收听到我们的次区域:
<input type="checkbox" :id="subregion[0].subregion" v-model="subregionCheck" :value="subregion[0].subregion" @click="checkAllCountries(subregion)">
,然后指定方法(只要你不使用ES6,我需要委派“这个”变量):
checkAllCountries: function (subregion) {
var that = this;
if (this.subregionCheck.indexOf(subregion[0].subregion) > -1) {
subregion.forEach(function (element) {
if (that.countryCheck.indexOf(element.name) <= -1) {
that.countryCheck.push(element.name);
}
});
}
else {
subregion.forEach(function (element) {
that.countryCheck.splice(that.countryCheck.indexOf(element.name), 1);
})
}
},
现在我们需要一种方法来取消选中子区域复选框,如果其中一个国家未选中。点击监听器添加到国家复选框:
<input type="checkbox" :id="country.name" v-model="countryCheck" :value="country.name" @click="checkSubregion(subregion)">
然后指定方法:
checkSubregion: function (country) {
if ((this.countryCheck.indexOf(country.name) <= -1) && this.subregionCheck.indexOf(country.subregion) > -1) {
this.subregionCheck.splice(this.subregionCheck.indexOf(country.subregion), 1);
}
},
Working fiddle