v-for在vue.js中不使用html元素 [英] v-for without using html element in vue.js

查看:117
本文介绍了v-for在vue.js中不使用html元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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>

脚本

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

在这里您可以看到,要显示带有我必须与父辈一起访问的标签的Hobby,

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

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

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

这是令人讨厌的例外情况 [Vue警告]:实例上未定义属性或方法爱好"

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

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

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

推荐答案

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

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>

这篇关于v-for在vue.js中不使用html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆