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()拼接。

希望对同学们有帮助!谢谢!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值