v-for 不使用 vue.js 中的 html 元素

新手上路,请多包涵

我是 Vue.js 的新手

我正在为输入元素实践准备演示,这是我的代码。

HTML

 <div id="inputDiv">
  <form action="">
    <input type="text" v-model="first_name">
    <input type="text" v-model="last_name">
    <input type="email" v-model="email">
    <div>
      <input type="radio" :name="gender" v-model="gender" value="male">Male
      <input type="radio" :name="gender" v-model="gender" value="female">Female
    </div>
    <textarea v-model="address" id="" cols="30" rows="10"></textarea>
    <br>
    <div v-for="hobby in hobbies">
      <input type="checkbox" v-model="userHobbies" v-bind:value="hobby">{{hobby}}
    </div>
  </form>
</div>

脚本

const inputApp = new Vue({
  el: '#inputDiv',
  data: {
    first_name: '',
    last_name: '',
    email: '',
    gender: 'male',
    address: '',
    userHobbies:[],
    hobbies: ['Reading', 'Cricket', 'Cycling', 'Hiking']
  }
})

在这里你可以看到,要用标签显示 Hobby 我必须用 parent 迭代,

添加一个 div 不是我想要的,如果我愿意 v-for 在输入元素中,如:

 <input
  type="checkbox"
  v-for="hobby in hobbies"
  v-model="userHobbies"
  v-bind:value="hobby"
>{{hobby}}

thin it’s thowing exception [Vue warn]: 实例上未定义属性或方法“爱好”

我的问题是有没有其他方法可以在不使用 HTML 元素的情况下对对象元素使用 v-for

原文由 Chintan7027 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 544
1 个回答

将其包装在 template 标签中,因为模板标签不会出现在最终呈现的 HTML 中:

 <template v-for="hobby in hobbies">
    <input type="checkbox" v-model="userHobbies" v-bind:value="hobby">{{hobby}}
</template>

或者更好的是,改进您的标记语义并使用标签标签:

 <label v-for="hobby in hobbies">
    <input type="checkbox" v-model="userHobbies" v-bind:value="hobby"> {{hobby}}
</label>

原文由 James Coyle 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题