遇到这种情况怎么写更优雅?

作者站长头像
站长
· 阅读数 11
  <vxe-column field="sourceDataType" title="源数据类型" :edit-render="{}">
    <template #default="{ row }">
      <span>{{sourceDataTypeOptions.find(x => x.value === row.sourceDataType) ? 
              sourceDataTypeOptions.find(x => x.value === row.sourceDataType).label : ''
      }}</span>
    </template>
    <template #edit="{ row }">
      <el-select
        style="width: 100%"
        v-model="row.sourceDataType"
        filterable
        placeholder="请选择源数据类型"
      >
        <el-option
          v-for="item in sourceDataTypeOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        ></el-option>
      </el-select>
    </template>
  </vxe-column>

代码如上,sourceDataTypeOptions是一个数组,我想判断sourceDataTypeOptions.find(x => x.value === row.sourceDataType)找到值的时候取这个值的labe,没有找到值得时候用空字符串。不写format函数,直接在这里写怎样才能写得更优雅

回复
1个回答
avatar
test
2024-07-14

(sourceDataTypeOptions.find(x => x.value === row.sourceDataType)||{}).label||''

通用给默认值的写法

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容