项目升级到vue3,那对应的组件重新升级了下,但仅只是针对vue2版本的改造,所以很多地方有瑕疵,代码供大家参考和指点,目前项目够用,但也希望大家提出更好的优化方案
vue2版本
多选checkbox 组件源码
<template>
<div class="dh-field ">
<div class="van-hairline--bottom">
<van-field
v-model="resultLabel"
v-bind="$attrs"
readonly
:is-link="$attrs.disabled === undefined"
error-message-align='right'
input-align="right"
@click="showPopu($attrs.disabled as any)"
class="dh-cell"
/>
<van-popup v-model:show="data.showPop" position="bottom" class="" >
<div class="van-picker__toolbar">
<button type="button" class="van-picker__cancel" @click="cancel">取消</button>
<div class="van-ellipsis van-picker__title">{{$attrs.label}}<span v-if="max">(最多选{{max}}个)</span></div>
<button type="button" class="van-picker__confirm" @click="onConfirm">确认</button>
</div>
<div class="checkbox-con" style="max-height:264px;overflow-y:auto">
<van-field v-model="data.searchVal" placeholder="搜索" @update:model-value="search" v-if="isSearch" input-align="left"/>
<van-cell title="全选" v-if="!max">
<template #right-icon>
<van-checkbox name="all" @click="toggleAll" v-model="data.checkedAll"/>
</template>
</van-cell>
<van-cell title="不包含" v-if="noIncludeOption">
<template #right-icon>
<van-checkbox name="00" @click="unToggleAll" v-model="data.unCheckedAll"/>
</template>
</van-cell>
<van-checkbox-group :max="max" v-model="data.checkboxValue" @change="change" ref="checkboxGroup">
<van-cell-group>
<van-cell
v-for="(item, index) in data.columnsData"
clickable
:key="item[option.value]"
:title="item[option.label]"
@click="toggle(index,item)"
>
<template #right-icon>
<van-checkbox :name="item[option.value]" ref="checkboxes" />
</template>
</van-cell>
</van-cell-group>
</van-checkbox-group>
</div>
</van-popup>
</div>
</div>
</template>
<script setup lang="ts">
import type { CheckboxGroupInstance } from 'vant';
//更新发送model
const emit = defineEmits(['update:modelValue','confirm','change','cancel','clickItem'])
const props=defineProps({
modelValue: {
type: Array<object | number | string>,
default: false
},
columns: {
type: Array<object | number | string>,
default: function () {
return []
}
},
option: {
type: Object,
default: function () {
return { label: 'name', value: 'code' }
}
},
isSearch: {
type: Boolean,
default: false
},
max: { // 最大可选
type: [Number, String],
default: 0
},
noIncludeOption: { // 是否有不包含选项
type: Boolean,
default: false
},
})
interface Config {
searchVal: string;
columnsData: Array<any>;
checkboxValue: Array<any>;// 所有选中项的标识符
checkedAll: boolean ;
resultValue: Array<any>;
showPop:boolean ,
unCheckedAll: boolean
}
const data:Config=reactive({
searchVal: '',
columnsData: JSON.parse(JSON.stringify(props.columns)),
checkboxValue:[],
checkedAll: false,
resultValue:[],
showPop:false,
unCheckedAll:false
})
//回显label
const resultLabel=computed({
get () {
let columns:any[] = JSON.parse(JSON.stringify(props.columns))
if (props.noIncludeOption) { // 开启不包含
columns.unshift({ name: '不包含', code: '00' })
}
const res = columns.filter(item => {
return data.resultValue?.indexOf(item[props.option.value] ) > -1
})
const resLabel = res.map(item => {
return item[props.option.label]
})
return resLabel.join(',')
},
set () {
}
})
const showPopu= (disabled:boolean | undefined =false)=> {
data.columnsData = JSON.parse(JSON.stringify(props.columns))
if (disabled !== undefined && disabled !== false) {
return false
} else {
data.showPop = !data.showPop
}
}
//因为props的数据是只读,不能用于绑定model,所以需要重新定义赋值
watch(()=>props.modelValue, (newVal, oldVal) => {
data.resultValue=newVal
data.checkboxValue=JSON.parse(JSON.stringify(newVal))
},{
immediate:true,
deep:true
})
//搜索
const search= (val:string)=> {
if (val) {
data.columnsData = data.columnsData.filter(item => {
return item[props.option.label]?.indexOf(val) > -1
})
} else {
data.columnsData = JSON.parse(JSON.stringify(props.columns))
}
}
//获取选中值得完整数据
const getData= (val:any)=> {
const res:any = data.columnsData.filter(item => {
return val.indexOf(item[props.option.value]) > -1
})
return res || ''
}
//操作事件
const onConfirm= ()=> {//确认
data.resultValue = data.checkboxValue
emit('confirm', data.resultValue, getData(data.resultValue))
}
const change= (val:any)=> {//数据切换未确认
emit('change', val, getData(val))
}
const cancel =(val:any)=> {//取消
data.resultValue = []
emit('cancel')
}
watch(()=>data.resultValue, (newVal, oldVal) => {
//当结果确定后,重置数据
data.searchVal = ''
data.columnsData = JSON.parse(JSON.stringify(props.columns))
data.showPop =false
emit('update:modelValue',newVal)
},{
immediate:true,
deep:true
})
// 全选非全选
const checked = ref([]);
const checkboxGroup = ref<CheckboxGroupInstance>();
const toggle =(index:number | string,item:any) =>{
data.unCheckedAll = false
data.checkboxValue = data.checkboxValue.filter(item => item != '00')
emit('clickItem', item)//单条数据点击
checked?.value[index]?.toggle()
}
const toggleAll =() =>{
data.unCheckedAll = false
data.checkboxValue = data.checkboxValue.filter(item => item != '00')
checkboxGroup?.value?.toggleAll(data.checkedAll)
}
const unToggleAll= () =>{ // 不包含
checkboxGroup?.value?.toggleAll(false)
data.checkboxValue = ['00']
}
//全选非全选监听
watch(()=>[data.columnsData,data.checkboxValue], (newVal, oldVal) => {
const columnsData=newVal[0]
const checkboxValue=newVal[1]
const reg=columnsData.length && columnsData.length === data.checkboxValue.length
const reg2=checkboxValue.length && checkboxValue.length === data.columnsData.length
if (reg || reg2) {
data.checkedAll = true
} else {
data.checkedAll = false
}
},{
immediate:true,
deep:true
})
</script>
<style lang="scss" scoped>
.dh-field {
padding: 0 16px;background:#fff;
.dh-cell.van-cell{padding: 10px 0;}
.dh-cell.van-cell--required::before{left: -8px;}
.van-popup{border-radius: 20px 20px 0 0;}
}
</style>
使用,和van-checkbox一样,新增个性化自定义option和搜索
<van-field-checkbox
ref="check"
label="物料类型"
placeholder="请选择"
v-model="value1"
:columns="columns"
:option="{label:'name',value:'code'}"
/>
const value1=ref([''])
const columns=reactive([
{ name: '1', code: '11' },
{ name: '2', code: '22' }
])
新增属性
:columns="columns"---------------------可选择的数据,只接受key-value格式的对象集合,[1,2,3]不可以
:option="{label:'name',value:'code'}"--数据的配置格式,默认label(显示的文字),value(具体值)
:isSearch------------------------------是否开启搜索
Events 类似 van-checkbox,多返回一个参数,
|-confirm -- 点击完成按钮时触发 -- 返回:选中[value:string]值Arrray,选中[单条数据:obj]值Arrray-|
|-cancel -- 点击取消按钮时触发
|-change -- 选项改变时触发 -- 返回:选中[value:string]值Arrray,选中[单条数据:obj]值Arrray-|
|-clickItem --- 点击单条选项时候触发 --返回:选中值的obj|
select 单选组件源码
<template>
<div class="dh-field">
<div class=" van-hairline--bottom">
<van-field
v-model="resultLabel"
v-bind="$attrs"
readonly
:is-link="$attrs.disabled === undefined || $attrs.disabled === false"
input-align="right"
@click="showPopu($attrs.disabled as any)"
error-message-align='right'
class="dh-cell"
/>
<van-popup v-model:show="data.show" position="bottom">
<van-field v-model="data.searchVal" class="search" :placeholder="searchPh" @update:model-value="search" v-if="isSearch" input-align="left"/>
<van-picker
v-bind="$attrs"
:columns="data.columnsData"
:columns-field-names="columnsFieldNames"
show-toolbar
v-model="data.selectedValues"
@cancel="cancel"
@confirm="onConfirm"
@change="change"
/>
</van-popup>
</div>
</div>
</template>
<script setup lang="ts">
//更新发送model
const emit = defineEmits(['update:modelValue','confirm','change','cancel','click'])
const props=defineProps({
modelValue: {
type: [String,Number],
default: ''
},
columns: {
type: Array<object | number | string>,
default: function () {
return []
}
},
columnsFieldNames: {
type: Object,
default: function () {
return { text: 'text', value: 'value' }
}
},
isSearch: {
type: Boolean,
default: false
},
searchPh: {
type: String,
default: '输入搜索信息'
},
})
interface Config{
show: boolean,
searchVal:string,
resultValue: string | number,
columnsData: Array<any>,
default_index: number, // 默认选中项索引
selectedValues:Array<any>
}
const data:Config=reactive({
show: false,
searchVal: '',
resultValue: props.modelValue,
columnsData: [],
default_index: 0 ,// 默认选中项索引
selectedValues:[]
})
//回显label
const resultLabel=computed({
get () {
const res = props.columns.filter(item => {
const val = item[props['columnsFieldNames'].value]
return val === data.resultValue
})
let label = ''
if (res.length) {
label = res[0][props['columnsFieldNames'].text]
}
return label || props.modelValue
},
set () {
}
})
//因为props的数据是只读,不能用于绑定model,所以需要重新定义赋值
watch(()=>props.modelValue, (newVal, oldVal) => {
data.resultValue=newVal
data.selectedValues=[newVal]
},{
immediate:true,
deep:true
})
//搜索
const search =(val:string)=> {
if (val) {
data.columnsData = props.columns.filter(item => {
const res = item[props['columnsFieldNames'].text]
return res.indexOf(val) > -1
})
} else {
data.columnsData = JSON.parse(JSON.stringify(props.columns))
}
}
//操作
const onConfirm =(value:any) =>{
let val = ''
if (value) {
val = value.selectedValues[0]
}
data.resultValue = val
data.show = !data.show
emit('confirm', value, val)
emit('update:modelValue', val)
}
const change= (value:any)=> {
let val = ''
if (value) {
val = value.selectedValues[0]
}
emit('change', value, val)
}
const cancel =() =>{
data.show = !data.show
emit('cancel')
}
const showPopu= (disabled:boolean | undefined =false)=> {
data.columnsData = JSON.parse(JSON.stringify(props.columns))
data.resultValue = props.modelValue
if (disabled !== undefined && disabled !== false) {
return false
} else {
data.show = !data.show
}
}
watch(()=>data.resultValue, (newVal, oldVal) => {
data.searchVal = ''
data.columnsData = JSON.parse(JSON.stringify(props.columns))
},{
immediate:true,
deep:true
})
</script>
<style lang="scss" scoped>
.dh-field {
padding: 0 16px;background:#fff;
.dh-cell.van-cell{padding: 10px 0;}
.dh-cell.van-cell--required::before{left: -8px;}
.van-popup{border-radius: 20px 20px 0 0;}
}
::v-deep .search .van-field__value{background: #f7f7f7;padding: 2px;}
</style>
使用
<van-field-select-picker
v-model="selectval"
isSearch
label="select"
:columns="columns"
:columns-field-names="{text:'name',value:'code',children: 'children' }" @confirm="confirmDate3" />
const selectval=ref('11')
const columns=reactive([
{ name: '1', code: '11' },
{ name: '2', code: '22' }
])
const confirmDate3=(val:any,val2:string)=>{
console.log(val,val2)
}
Events 同 vant-picker
|-confirm -- 点击完成按钮时触发 -- 单列:选中[整个数据]的值Aarry,选中的value值string-|
|-cancel -- 点击取消按钮时触发-|
|-change -- 选项改变时触发 -- 单列:选中[整个数据]的值Aarry,选中的value-|
属性
label-width ---------------------------label的一个宽度设置
label="单选select"---------------------label文字
:columns="columns"---------------------可选择的数据,只接受key-value格式的对象集合,[1,2,3]不可以
:isSearch------------------------------是否开启搜索