Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

javascript - v-for without using html element in vue.js

I am newbie to Vue.js

I am preparing demo for input elements practices, here is my code.

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>

Script

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

Here you can see, to display Hobby with label I have to iterate with parent ,

adding a div is not something I wants, If I will v-for in input element like:

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

thin it's thowing exception [Vue warn]: Property or method "hobby" is not defined on the instanc

My question is is there any alternative to use v-for over object elements without using HTML element ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Wrap it in a template tag as the template tag will not appear in the final rendered HTML:

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

Or even better, improve your markup semantics and use a label tag:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...