vue 实现自定义下拉多选框控件 Checkbox Select
2022/7/29 23:29:57
本文主要是介绍vue 实现自定义下拉多选框控件 Checkbox Select,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
网上看了别人写的控件,bug太多,于是仿着自己写了一个
控件:checkableSelect.vue
<template> <el-select v-bind="$attrs" v-model="selectedValue" multiple @change="changeSelect"> <el-option v-if="dataSource.length" label="全选" :value="selectAll"> <el-checkbox v-model="selectedAll" @click.prevent.native>全选</el-checkbox> </el-option> <el-option v-for="item in dataSource" :key="item[valueProp]" :label="item[textProp]" :value="item[valueProp]"> <el-checkbox v-model="item[checkedProp]" @click.prevent.native>{{item[textProp]}}</el-checkbox> </el-option> </el-select> </template> <script> import Linq from "linq"; export default { name: "checkableSelect", model: { event: "change" }, props: { value: Array, source: Array, textProp: String, valueProp: String, checkedProp: String }, data() { return { selectAll: this.newGuid(), selectedAll: false } }, computed: { selectedValue: { get: function () { return this.value; }, set: function (val) { if (val.includes(this.selectAll)) this.selectedAll = !this.selectedAll; this.dataSource.forEach(item => { if (val.includes(this.selectAll)) { item[this.checkedProp] = this.selectedAll; } else { if (val.includes(item[this.valueProp])) item[this.checkedProp] = true; else item[this.checkedProp] = false; } }); if(Linq.from(this.dataSource).all(item=> item[this.checkedProp] == true )) this.selectedAll = true; else this.selectedAll = false; this.$forceUpdate(); } }, dataSource: { get: function () { return this.source; }, set: function (val) { //debugger } } }, watch: { selectedValue: function (newValue) { //debugger }, dataSource: function (newValue) { //debugger if(this.dataSource.length > 0 && Linq.from(this.dataSource).all(item=> item[this.checkedProp] == true )) this.selectedAll = true; else this.selectedAll = false; } }, created() { }, methods: { changeSelect(val) { var values = Linq.from(this.dataSource).where(x => x[this.checkedProp]).select(x => x[this.valueProp]).toArray(); this.$emit("change", values); }, newGuid() { return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[x]/g, function (c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); var result = v.toString(16); return result; }); } } } </script>
使用:
import checkableSelect from "../tools/checkableSelect"
<checkableSelect style="width:100%;" v-model="gradesViewModel" :source="grades" @change="gradesChange" :textProp="'label'" :valueProp="'value'" placeholder="请选择适用年级"> </checkableSelect>
这篇关于vue 实现自定义下拉多选框控件 Checkbox Select的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-16Vue3资料:新手入门必读教程
- 2024-11-16Vue3资料:新手入门全面指南
- 2024-11-16Vue资料:新手入门完全指南
- 2024-11-16Vue项目实战:新手入门指南
- 2024-11-16React Hooks之useEffect案例详解
- 2024-11-16useRef案例详解:React中的useRef使用教程
- 2024-11-16React Hooks之useState案例详解
- 2024-11-16Vue入门指南:从零开始搭建第一个Vue项目
- 2024-11-16Vue3学习:新手入门教程与实践指南
- 2024-11-16Vue3学习:从入门到初级实战教程