也许我正在以错误的方式处理这个问题......但我正在尝试使用循环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
}
}
});
Run Code Online (Sandbox Code Playgroud)
v-for需要 a Number,但您给它一个字符串(所选值)。将其转换为 a 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>
Run Code Online (Sandbox Code Playgroud)
为了完整起见,另一种方法(根据@HusamIbrahim)是用 注释 v-model 引用.number,这将自动进行转换。
<select
name="number_students_enrolling"
v-model.number="formFields.numberStudentsEnrolling"
>
Run Code Online (Sandbox Code Playgroud)
这是一个codesandbox: https: //codesandbox.io/s/xzy6or9qo
| 归档时间: |
|
| 查看次数: |
1616 次 |
| 最近记录: |