項(xiàng)目升級(jí)到vue3,那對(duì)應(yīng)的組件重新升級(jí)了下乏屯,但僅只是針對(duì)vue2版本的改造根时,所以很多地方有瑕疵,代碼供大家參考和指點(diǎn)辰晕,目前項(xiàng)目夠用蛤迎,但也希望大家提出更好的優(yōu)化方案
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}}個(gè))</span></div>
<button type="button" class="van-picker__confirm" @click="onConfirm">確認(rèn)</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';
//更新發(fā)送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: { // 是否有不包含選項(xiàng)
type: Boolean,
default: false
},
})
interface Config {
searchVal: string;
columnsData: Array<any>;
checkboxValue: Array<any>;// 所有選中項(xiàng)的標(biāo)識(shí)符
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
}
}
//因?yàn)閜rops的數(shù)據(jù)是只讀,不能用于綁定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))
}
}
//獲取選中值得完整數(shù)據(jù)
const getData= (val:any)=> {
const res:any = data.columnsData.filter(item => {
return val.indexOf(item[props.option.value]) > -1
})
return res || ''
}
//操作事件
const onConfirm= ()=> {//確認(rèn)
data.resultValue = data.checkboxValue
emit('confirm', data.resultValue, getData(data.resultValue))
}
const change= (val:any)=> {//數(shù)據(jù)切換未確認(rèn)
emit('change', val, getData(val))
}
const cancel =(val:any)=> {//取消
data.resultValue = []
emit('cancel')
}
watch(()=>data.resultValue, (newVal, oldVal) => {
//當(dāng)結(jié)果確定后替裆,重置數(shù)據(jù)
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)//單條數(shù)據(jù)點(diǎn)擊
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']
}
//全選非全選監(jiān)聽
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一樣,新增個(gè)性化自定義option和搜索
<van-field-checkbox
ref="check"
label="物料類型"
placeholder="請(qǐng)選擇"
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"---------------------可選擇的數(shù)據(jù)辆童,只接受key-value格式的對(duì)象集合宜咒,[1,2,3]不可以
:option="{label:'name',value:'code'}"--數(shù)據(jù)的配置格式,默認(rèn)label(顯示的文字)把鉴,value(具體值)
:isSearch------------------------------是否開啟搜索
Events 類似 van-checkbox故黑,多返回一個(gè)參數(shù),
|-confirm -- 點(diǎn)擊完成按鈕時(shí)觸發(fā) -- 返回:選中[value:string]值A(chǔ)rrray,選中[單條數(shù)據(jù):obj]值A(chǔ)rrray-|
|-cancel -- 點(diǎn)擊取消按鈕時(shí)觸發(fā)
|-change -- 選項(xiàng)改變時(shí)觸發(fā) -- 返回:選中[value:string]值A(chǔ)rrray,選中[單條數(shù)據(jù):obj]值A(chǔ)rrray-|
|-clickItem --- 點(diǎn)擊單條選項(xiàng)時(shí)候觸發(fā) --返回:選中值的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">
//更新發(fā)送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, // 默認(rèn)選中項(xiàng)索引
selectedValues:Array<any>
}
const data:Config=reactive({
show: false,
searchVal: '',
resultValue: props.modelValue,
columnsData: [],
default_index: 0 ,// 默認(rèn)選中項(xiàng)索引
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 () {
}
})
//因?yàn)閜rops的數(shù)據(jù)是只讀庭砍,不能用于綁定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 -- 點(diǎn)擊完成按鈕時(shí)觸發(fā) -- 單列:選中[整個(gè)數(shù)據(jù)]的值A(chǔ)arry,選中的value值string-|
|-cancel -- 點(diǎn)擊取消按鈕時(shí)觸發(fā)-|
|-change -- 選項(xiàng)改變時(shí)觸發(fā) -- 單列:選中[整個(gè)數(shù)據(jù)]的值A(chǔ)arry怠缸,選中的value-|
屬性
label-width ---------------------------label的一個(gè)寬度設(shè)置
label="單選select"---------------------label文字
:columns="columns"---------------------可選擇的數(shù)據(jù)诗轻,只接受key-value格式的對(duì)象集合,[1,2,3]不可以
:isSearch------------------------------是否開啟搜索