vue中全选功能的实现,用实例说明
时间: 2023-03-11 15:16:17 浏览: 46
可以使用以下代码实现Vue中的全选功能: <template>
<div>
<input type="checkbox" name="checkAll" id="checkAll" v-model="checkedAll" @change="checkAllChange" />
<label for="checkAll">全选</label>
<ul>
<li v-for="item in items" :key="item.id">
<input type="checkbox" name="checkItem" :value="item.id" v-model="checkedItems" @change="checkChange"/>
<label :for="`check-${item.id}`">{{item.name}}</label>
</li>
</ul>
</div>
</template><script>
export default {
data () {
return {
checkedAll: false,
checkedItems: [],
items: [
{id: 1, name: 'item1'},
{id: 2, name: 'item2'},
{id: 3, name: 'item3'},
{id: 4, name: 'item4'},
]
}
},
methods: {
checkAllChange () {
if (this.checkedAll) {
this.checkedItems = this.items.map(item => item.id)
} else {
this.checkedItems = []
}
},
checkChange () {
if (this.checkedItems.length === this.items.length) {
this.checkedAll = true
} else {
this.checkedAll = false
}
}
}
}
</script>可以通过在模板中添加复选框,然后使用v-model将复选框的值绑定到data中的checkedAll和checkedItems,并使用@change事件来监听复选框的状态变化,实现全选的功能。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)