赞
踩
今天开发过程中遇到一个需求:要多选,且可以选全部,最少选一个,总结了下,具体代码如下:
// 结构代码:
<el-select v-model="searchForm.vipId" multiple collapse-tags placeholder="请选择" @change="changeSelect" @remove-tag="removeTag">
<el-option label="全部" value="0" @click.native="selectAll" />
<el-option v-for="(item, index) in vipList" :key="index" :label="item.name" :value="item.value" />
</el-select>
// 数据结构:
searchForm: {
vipId: ['0', '1', '2', '3']
},
vipList: [
{ name: '游客', value: '1', disable: false },
{ name: '免费会员', value: '2', disable: false },
{ name: '付费会员', value: '3', disable: false }
]
// 方法: selectAll() { if (this.searchForm.vipId.length < this.vipList.length) { this.searchForm.vipId = [] this.vipList.map((item) => { this.searchForm.vipId.push(item.value) }) this.searchForm.vipId.unshift('0') } else { this.searchForm.vipId = ['0', '1', '2', '3'] } }, changeSelect(val) { // debugger console.log(val) if (!val.includes('0') && val.length === this.vipList.length) { this.searchForm.vipId.unshift('0') } else if (val.includes('0') && (val.length - 1) < this.vipList.length) { this.searchForm.vipId = this.searchForm.vipId.filter((item) => { return item !== '0' }) // this.searchForm.vipId = ['0', '1', '2', '3'] console.log(this.searchForm.vipId) } if (val.length === 0) { this.searchForm.vipId = ['0', '1', '2', '3'] } }, removeTag(val) { if (val === '0') { // this.searchForm.vipId = [] this.searchForm.vipId = ['0', '1', '2', '3'] // 这里做了处理,当删去全部选项时候,默认选中所有内容 } } // 注:下面这里是我自己查询的接口方法里数据处理,包括分页参数page和查询参数searchOption const { page, searchOption } = this // alert(searchOption.vipId.length) if (searchOption.vipId.length === 4) { searchOption.vipId = ['0'] } console.log(typeof (searchOption.vipId), searchOption.vipId, 'vip') if (typeof (searchOption.vipId) === 'object') { searchOption.vipId = searchOption.vipId.join(',') // 因为传给后端的数据用的是formData格式,所以这里需要判断下数据类型,为数组的时候需要先转成字符串格式,为字符串的时候就不用管,默认值 // 传给后端的数据直接用{...page,...searchOption}就行了 }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。