valueToLabel過濾器

背景

在crm中,table展示時,字段返回的是value,而希望展示成label,此時可以用一個valueToLabel過濾器進行轉(zhuǎn)換。

使用

<el-table-column prop="status" :label="$t('advert.itemStatus')" align="center">
   <template slot-scope="scope">
     {{ scope.row.status | valueToLabel($t('data.statusList')) }}
   </template>
</el-table-column>
<el-table-column :label="'APP'" prop="appId" width="100" align="center">
   <template slot-scope="scope">
     {{ scope.row.appId | valueToLabel(dic_apps, 'name', 'value') }}
   </template>
</el-table-column>

valueToLabel實現(xiàn)

/**
 * 通過val匹配與arr中與valueKey的值相同的數(shù)據(jù),并返回labelKey對應(yīng)的值
 * @param {*} arr 數(shù)據(jù)列表
 * @param {*} val 值
 * @param labelKey 需要返回的數(shù)據(jù)key 默認為 label
 * @param valueKey  val對應(yīng)的數(shù)據(jù)key 默認為 value
 */
export function valueToLabel(val, arr, labelKey, valueKey) {
  let label = '';
  if (val === '' || val === null || !arr instanceof Array || arr.length == 0) {
    return '';
  }
  labelKey = labelKey || 'label';
  valueKey = valueKey || 'value';
  const item = arr.find(obj => obj[valueKey] === val);
  if (item && item[labelKey] !== undefined) {
    label = item[labelKey];
  } else {
    label = val;
  }
  return label;
}

arrToLabel實現(xiàn)

有時,table字段返回的是一個value數(shù)組,或者拼的字符串,依然希望轉(zhuǎn)成對應(yīng)的lable。在valueToLabel的基礎(chǔ)上處理一下即可。

export function arrToLabel(val, arr, labelKey, valueKey, defaultVal) {
  let arr_r = []
  let val_arr = val instanceof Array ? val : val==null ? [] :  val.split(',')
  for (let i = 0; i < val_arr.length; i++) {
    const element = val_arr[i];
    let label = valueToLabel(element, arr, labelKey, valueKey, defaultVal)
    arr_r.push(label)
  }
  return arr_r.join(',')
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容