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}}

细说是个例外[Vue警告]:实例上未定义属性或方法“爱好”


我的问题是是否可以在不使用HTML元素的情况下对对象元素使用v-for?


慕慕森
浏览 656回答 3
3回答

慕姐4208626

将其包装在template标签中,因为模板标签不会出现在最终呈现的HTML中:<template v-for="hobby in hobbies">&nbsp; &nbsp; <input type="checkbox" v-model="userHobbies" v-bind:value="hobby">{{hobby}}</template>甚至更好的是,改善标记语义并使用标签标记:<label v-for="hobby in hobbies">&nbsp; &nbsp; <input type="checkbox" v-model="userHobbies" v-bind:value="hobby"> {{hobby}}</label>

千万里不及你

您可以在div内添加模板,因为模板未呈现到DOM:&nbsp; <div id="inputDiv">&nbsp; &nbsp; <form action>&nbsp; &nbsp; &nbsp; <input type="text" v-model="first_name">&nbsp; &nbsp; &nbsp; <input type="text" v-model="last_name">&nbsp; &nbsp; &nbsp; <input type="email" v-model="email">&nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; <input type="radio" :name="gender" v-model="gender" value="male">Male&nbsp; &nbsp; &nbsp; &nbsp; <input type="radio" :name="gender" v-model="gender" value="female">Female&nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; <textarea v-model="address" id cols="30" rows="10"></textarea>&nbsp; &nbsp; &nbsp; <br>&nbsp; &nbsp; &nbsp; <template v-for="hobby in hobbies">&nbsp; &nbsp; &nbsp; &nbsp; <input type="checkbox" v-model="userHobbies" v-bind:value="hobby">&nbsp; &nbsp; &nbsp; &nbsp; {{hobby}}&nbsp; &nbsp; &nbsp; </template>&nbsp; &nbsp; </form>&nbsp; </div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript