Vue.js-对动态范围值使用v-for

时间:2018-12-04 18:54:50

标签: vue.js

也许我正在以错误的方式进行操作...但是我试图使用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
    }
  }
});

enter image description here   enter image description here

1 个答案:

答案 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"
>

这是一个代码框:https://codesandbox.io/s/xzy6or9qo