vue2 简洁的行政区划选择组件封装
vue2 简洁的行政区划选择组件封装
// 判断变量是否为 null 或 undefined
export function isNullOrEmpty(value) {
return value === null || value === undefined || value === ''
}
// 判断变量是否为 null 或 undefined
export function isNullOrUndefined(value) {
return value === null || value === undefined
}
<script>
import { isNullOrEmpty, isNullOrUndefined } from '@utils/index'
export default {
name: 'RegionSelect',
props: {
placeholder: { type: String, default: '请选择行政区' },
clearable: { type: Boolean, default: true },
showAllLevels: { type: Boolean, default: true },
value: { type: [String, Array], default: '' },
label: String,
props: {
type: Object,
default() {
return {}
}
},
options: {
type: Array,
default() {
return []
}
}
},
watch: {
value: {
handler(modelValue) {
this.modelValue = modelValue
}
}
},
computed: {
listMap() {
const { options, config } = this
const { label, value, children } = config
const map = new Map()
const deep = (list = []) => {
list.forEach(item => {
map.set(item[value], {
...item,
label: item[label],
value: item[value]
})
if (item[children] && item[children].length) {
deep(item[children])
}
})
}
deep(options)
return map
},
config() {
return {
multiple: false,
label: 'label',
value: 'value',
children: 'children',
// 是否可以任选一级
checkStrictly: false,
// 次级菜单的展开方式 click hover
expandTrigger: 'hover',
...this.props
}
}
},
data() {
return {
modelValue: this.value
}
},
methods: {
handleChange(codeArray) {
this.$refs.regionCodeOptionsRef.dropDownVisible = false //监听值发生变化就关闭它
if (this.config.multiple) {
this.modelValue = codeArray
} else {
let code = codeArray[codeArray.length - 1]
if (isNullOrUndefined(code)) {
code = ''
}
this.modelValue = code
}
this.$emit('input', this.modelValue)
this.$emit('update:label', this.listMap.get(this.modelValue)?.label)
this.$emit('change', this.modelValue)
}
}
}
</script>
<template>
<el-cascader
ref="regionCodeOptionsRef"
:value="modelValue"
:options="options"
:show-all-levels="showAllLevels"
:clearable="clearable"
:props="config"
:style="{ width: '100%' }"
v-bind="{ ...$attrs, ...$props }"
@change="handleChange"
/>
</template>
<style scoped lang="scss"></style>