问题一:el-select值不匹配导致回显id(此时只针对单选进行处理)

el-select数据的回显是根据id去匹配值的,最近项目出现了回显id的情况,原因是没有匹配的option

问题场景图如下:

 解决方案

1、方法一:获取完值和下拉数据后,通过方法遍历有没有匹配id的选项,没有就强塞一个选项进去,然后回显

修改代码如下:

setData(list, id, name) {
    let item = list.some(item => item.id === id)
    if (item) {
      list.push({
        id: id,
        name: name
      })
    }
}
2、方法二:改el-select的源代码
先分析源代码,看为什么会回显id

  • 可以看到红框框住的部分,如果有匹配的值,就返回值,如果没有匹配上,就返回String(value),也就是id
  • 要想回显值,就得把红框框住的部分改掉,计划将newOption改改(代码如下);其中defaultValue就是我们希望回显的值
const label = (!isObject && !isNull && !isUndefined) ? String(value) : ''
const newOption = {
    value: value,
    currentLabel: this.defaultValue || label
}

用了一个defaultValue的prop,通过mixin添加defaultValue

新增element-mixin.js,代码如下:

export default Element => {
  Element.Select.mixins[Element.Select.mixins.length] = {
    props: {
      defaultValue: {
        type: String || Number,
        default: ''
      }
    }
  }
}

在main.js里面把mixin加上,源码getOption的修改也写这里

import Element from 'element-ui'
import addSelectDefaultValue from '@/mixins/element-mixin'
Element.Select.methods.getOption = function(value) {
  let option
  const isObject = Object.prototype.toString.call(value).toLowerCase() === '[object object]'
  const isNull = Object.prototype.toString.call(value).toLowerCase() === '[object null]'
  const isUndefined = Object.prototype.toString.call(value).toLowerCase() === '[object undefined]'

  for (let i = this.cachedOptions.length - 1; i >= 0; i--) {
    const cachedOption = this.cachedOptions[i]
    const isEqual = isObject
      ? getValueByPath(cachedOption.value, this.valueKey) === getValueByPath(value, this.valueKey)
      : cachedOption.value === value
    if (isEqual) {
      option = cachedOption
      break
    }
  }
  if (option) return option
  const label = (!isObject && !isNull && !isUndefined)
    ? String(value) : ''
  const newOption = {
    value: value,
    currentLabel: this.defaultValue || label
  }
  if (this.multiple) {
    newOption.hitState = false
  }
  return newOption
}
addSelectDefaultValue(Element)
使用方式
<el-select v-model="value" :default-value="'显示错误'" clearable placeholder="请选择">
    <el-option 
        v-for="item in options"
        :key="item.value"
        :label="item.label"
        :value="item.value"
    >
    </el-option>
</el-select>
效果图

其它需要关注的问题
  • 每次clear下拉数据的时候也会回显defaultvalue,需要添加clear的回调,将defaultvalu设为""
  • 源码的修改是直接写在main里面的,如果项目三方包是私有化的可以直接改源码用,如果不是建议用patch-package打补丁

问题二:el-select自带的搜索功能只能搜label不能搜value

待补充

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐