关于VanCascader默认值(地址code转换)
作者:不是LIsa.
这篇文章主要介绍了关于VanCascader默认值(地址code转换),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
VanCascader默认值(地址code转换)
我在使用VanCascader的时候,发现页面刷新进入时组件没有默认值,提示的是placeholder“请输入地址”
我希望进去时显示我传入的值
如:
- “湖北省武汉市洪山区”,(code:110101)
- 一般传入的是code值,故希望两者转化
话不多说上代码:
<script lang="ts" setup>
import { useCascaderAreaData } from '@vant/area-data'
import type { CascaderOption } from 'vant'
const props = defineProps<{
modelValue: string
}>()
const emit = defineEmits<{
(e: 'update:modelValue', v: string): void
}>()
const show = ref(false)
interface OptionWithParents {
option: CascaderOption | null
parent: CascaderOption | null
grandparent: CascaderOption | null
}
function findOptionWithParents(options: CascaderOption[], targetValue: string, parent: CascaderOption | null, grandparent: CascaderOption | null): OptionWithParents | null {
for (const option of options) {
if (option.value === targetValue)
return { option, parent, grandparent }
if (option.children && option.children.length > 0) {
const result = findOptionWithParents(option.children, targetValue, option, parent)
if (result)
return result
}
}
return null
}
function getLabelByValue(options: CascaderOption[], targetValue: string) {
const { option, parent, grandparent } = findOptionWithParents(options, targetValue, null, null)
if (option && parent && grandparent)
return [grandparent.text, parent.text, option.text].join('/')
return ''
}
const fieldValue = ref(props.modelValue)
const options = useCascaderAreaData()
function onFinish({ selectedOptions, value }: { selectedOptions: CascaderOption[]; value: string }) {
show.value = false
fieldValue.value = selectedOptions.map(option => option.text).join('/')
emit('update:modelValue', value)
}
nextTick(() => {
fieldValue.value = getLabelByValue(options, props.modelValue)
})
</script><template>
<van-field
:model-value="fieldValue"
is-link
readonly
label="所在地区"
placeholder="选择地区"
@click="show = true"
/>
<van-popup v-model:show="show" round position="bottom">
<van-cascader
:model-value="modelValue"
title="请选择所在地区"
:options="options"
@close="show = false"
@finish="onFinish"
/>
</van-popup>
</template>接下来就是运行结果图:

点击编辑,进入地址编辑页面,
如下图所示:

有默认值:
- 北京市/北京市/西城区了。
代码说明:
- 使用findOptionWithParents()获取你传入的modelValue值(如:”110101“)
- 获取你所需要得到的option选项(’东城区‘)
- 根据option获取父级(’北京市‘)
- 父级的父级(’北京市‘),再根据join()拼接
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
