关于VanCascader默认值(地址code转换)
更新时间:2024年07月02日 09:11:09 作者:不是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()拼接
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Vue CLI4 Vue.config.js标准配置(最全注释)
这篇文章主要介绍了Vue CLI4 Vue.config.js标准配置,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-06-06
Vue如何使用patch-package优雅地修改第三方依赖库
在前端开发中,有时我们需要对第三方依赖库进行修改以满足项目需求,patch-package 是一个优秀的工具,可以帮助我们优雅地管理这些修改,下面我们来看看具体操作吧2025-03-03
从Echarts报错中学习Vue3 ref和shallowRef区别及其组件二次封装demo
这篇文章主要介绍了从Echarts报错中学习Vue3 ref和shallowRef区别及其组件二次封装demo,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-11-11


最新评论