我使用Vue JS创建一个表单,允许用户根据需要添加或删除行。
在容器中,我创建了一个自定义Dependant
组件,其标题为 Dependent n ,其中N是数据数组中的位置+ 1.
我知道我应该能够在index
范围内使用v-for
变量的组件中获得此计数但是我相信我从组件中错误地访问它。
我的容器标记如下:
<div class="tab-pane" id="dependants">
<p>Enter the birth date and residential status of all dependants below.</p>
<ae-dependant v-for="dependant in dependants" :dob="dependant.dob" :at-home="dependant.atHome"></ae-dependant>
<button class="btn btn-primary" type="button" @click="addDependant"><i class="glyphicon glyphicon-plus"></i> Add Dependant</button>
</div>
我知道我总是可以把它当成道具,但我觉得我不需要这样做。
组件和辅助设备如下。
// TODO: Two way filter
Vue.filter('ISODate', function (value) {
return value.toISOString().substr(0,10);
})
var Dependant = Vue.extend({
props: ['dob','atHome'],
template: '<div class="form-horizontal">'
+ '<h4>Dependant {{ index + 1 }}</h4>'
+ '<div class="form-group">'
+ '<label for="dependantDOB{{ index + 1 }}" class="col-sm-2 control-label">Date of Birth</label>'
+ '<div class="col-sm-6">'
+ '<input type="date" class="form-control" id="dependantDOB{{ index + 1 }}" v-model="dob | ISODate">'
+ '</div><div class="col-sm-4"><div class="checkbox"><label>'
+ '<input type="checkbox" id="dependantRes{{ index + 1 }}" v-model="atHome"> <b>Living at Home?</b>'
+ '</label></div></div></div></div>'
})
// Register
Vue.component('ae-dependant', Dependant)
var Dependants = new Vue ({
el: '#dependants',
data: {
dependants: [{dob: new Date(),atHome: true}]
},
methods: {
addDependant: function () {
return this.dependants.push({dob: new Date(), atHome: true});
}
}
});
我应该如何访问组件中的index
?