v-for 不使用 vue.js 中的 html 元素 [英] v-for without using html element in vue.js
问题描述
我是 Vue.js 的新手
我正在准备输入元素实践的演示,这是我的代码.
HTML
<form action=""><输入类型=文本"v-model=first_name"><输入类型=文本"v-model="last_name"><输入类型=电子邮件"v-model=电子邮件"><div><输入类型=收音机":name="性别"v-model=性别"值=男性">男性<输入类型=收音机":name="性别"v-model=性别"值=女性">女性<textarea v-model="地址"id=""cols=30"行=10"></textarea><br><div v-for=爱好中的爱好"><输入类型=复选框"v-model=userHobbies"v-bind:value=爱好">{{爱好}}
</表单>
脚本
const inputApp = new Vue({el: '#inputDiv',数据: {名: '',姓: '',电子邮件: '',性别:'男',地址: '',用户爱好:[],爱好:['阅读'、'板球'、'骑自行车'、'远足']}})
在这里你可以看到,要显示带有标签的 Hobby,我必须与 parent 一起迭代,
添加 div 不是我想要的,如果我将 v-for
在输入元素中,例如:
thin it's thowing 异常 [Vue 警告]:属性或方法爱好"未在实例上定义
我的问题是有没有其他方法可以在不使用 HTML 元素的情况下在对象元素上使用 v-for ?
将其包裹在 template
标签中,因为模板标签不会出现在最终呈现的 HTML 中:
<input type="checkbox" v-model="userHobbies" v-bind:value="hobby">{{hobby}}模板>
或者更好的是,改进您的标记语义并使用标签标签:
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 ?
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屋!