也许我正在以错误的方式进行操作...但是我试图使用v-for
循环来复制/删除自定义组件x
次。 x
由上方的<select>
字段决定。我在初始页面加载时所做的工作,但是当您选择其他选项时,仅显示一个自定义组件(尽管x
已更新)。有人知道我在做什么错吗?
// here is the select field that defines the number of enrolling students
<select name="number_students_enrolling" v-model="formFields.numberStudentsEnrolling">
<option value="" default selected></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
// here is the custom component I'm trying to duplicate/remove dynamically
<div class="students-container">
<student v-for="n in formFields.numberStudentsEnrolling" :key="n" v-bind:index="n" >
</student>
</div>
// here is the custom component
Vue.component('student', {
props: ["index"],
template: `
<div class="input--student">
<div class="input--half">
<label>
<span class="d-block">
Student {{ index }} Name <span class="field--required">*</span>
</span>
<input type="text">
</label>
</div>
<div class="input-wrap input--half">
<label>
<span class="d-block">
Student {{ index }} DOB <span class="field--required">*</span>
</span>
<input type="text">
</label>
</div>
</div>
`
})
// Here is the Vue.js instance
var test = new Vue({
el: '#test',
data: {
formFields: {
numberStudentsEnrolling: 3
}
}
});
答案 0 :(得分:2)
v-for
需要一个Number
,但是您要给它一个字符串(选定的值)。将其转换为Number
,以便v-for
将其视为从1到N的范围:
<div class="students-container">
<student
v-for="n in Number(formFields.numberStudentsEnrolling)"
:key="n"
v-bind:index="n">
</student>
</div>
为完整起见,另一种方法(每个@HusamIbrahim)是用.number
注释v模型参考,这将自动进行转换。
<select
name="number_students_enrolling"
v-model.number="formFields.numberStudentsEnrolling"
>