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>

 




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM