不为别的,只为做一个连自己都羡慕的人

vue v-for 循环复选框-默认勾选第一个的实现方法

在帮朋友解决问题的时候,随手记录一下。

应用场景:在进行多选的时候一般默认显示第一个。

实现方法:纯vue实现

例子:<span v-for="(one,index) in site"><input type="checkbox" :checked="index == 0" style="vertical-align: middle;"><label>{{one.name}}</label></span>

实现代码具体如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue 测试实例 - 菜鸟教程(runoob.com)</title>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
  <span v-for="(one,index) in site"><input  type="checkbox" :checked="checked==index" @change="get(index)"><label>{{one.name}}</label></span>
  <span v-for="(item,index) in list"><input  type="checkbox" :checked="checkedMore.includes(index)" @change="getMore(index)"><label>{{item.name}}</label></span>
</div>
 
<script>
new Vue({
  el: '#app',
  data: {
        message: 'Hello Vue.js!',
        site:[{name:'454'},{sex:'55'}],
        list:[{name:''},{sex:''}],
        checked:0,  //通过设置变量,以及遍历列表的下表结合,去实现哪个复选框被选中。这种方法很常见。希望可以帮助到各位朋友
        checkedMore:[0]
  },
    methods:{
        get(index){
            this.checked = index;
            
        },
        getMore(index){
            this.checkedMore.push(index)
        }
    }
})
</script>
</body>
</html>

 



posted @ 2021-08-03 16:38  升级打怪  阅读(1191)  评论(0编辑  收藏  举报