vue的checkbox 用v-for 数组遍历怎么写
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
</head>
<body>
<div id='novfor'>
<input type="checkbox" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<hr/>
<div id="vfor">
<input v-for="item in list " type="checkbox" value="item" v-model="checkedNames">{{item}}
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<script>
new Vue({
el: '#novfor', // novfor
data: {
list: ['Jack','John','Mike'],
checkedNames: []
}
})
</script>
</body></html>
el :"#novfor" 用硬编码列表 是正常的,但是写成v-for="item in list " 就不对了
6 回复
你不能在input上用v-for ,你在input外面的div上用v-for
@SKandAV 怎么取得当前选择的节点 比如event.target 比如象ng里面
ng-click="select_current(item,$event)"
$scope.select_current = function(item,event){
item是对应的数组的元素 event.target是对应的页面元素
@yakczh v-for 的时候 这样 v-for="(item,index) in list" 这个index就是选择的节点
- el挂载错误,****https://cn.vuejs.org/v2/api/#el
- v-for 对item 也起不了作用
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
</head>
<body>
<div id="app">
<div id='novfor'>
<input type="checkbox" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<hr />
<div id="vfor">
<div v-for="item in list ">
<input type="checkbox" :value="item" v-model="checkedNames">{{item}}
</div>
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
</div>
<script>
new Vue({
el: '#app', // novfor
data: {
list: ['Jack', 'John', 'Mike'],
checkedNames: []
}
});
</script>
</body>
</html>
@chenkai0520 但这样就破坏了原来的页面结构 保持原来煌页面结构不变怎么写
@yakczh 你原先页面是错误的,vue的语法都没搞清楚, 你看看这两个有什么区别
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/vue@2.6.12/dist/vue.js"></script>
</head>
<body>
<div id='novfor'>
<input type="checkbox" value="Jack" v-model="checkedNames">
<label for="jack">Jack</label>
<input type="checkbox" value="John" v-model="checkedNames">
<label for="john">John</label>
<input type="checkbox" value="Mike" v-model="checkedNames">
<label for="mike">Mike</label>
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<hr />
<div id="vfor">
<input v-for="item in list " type="checkbox" :value="item" v-model="checkedNames">{{item}}
<br>
<span>Checked names: {{ checkedNames }}</span>
</div>
<script>
new Vue({
el: '#novfor', // novfor
data: {
list: ['Jack', 'John', 'Mike'],
checkedNames: []
}
})
new Vue({
el: '#vfor', // novfor
data: {
list: ['Jack', 'John', 'Mike'],
checkedNames: []
}
})
</script>
</body>
</html>