经常遇到只有一个id,让你通过id去找数组里对应的一些字段,为了方便封装一个方法以后可以直接调用
方法
/** * @description: 方法描述 * @arr {参数类型} 数组 * @id {参数类型} id * @idName {参数类型} id对应的字段 * @lableName {参数类型} 需要返回的字段名称 * @return 没有返回信息写 void / 有返回信息 {返回类型} 描述信息 */ getName(arr,id,idName,lableName){ //通过id获取数组名称 if(id||id=='0'){ const index = arr.findIndex((role) => role[idName] === id) return index>=0?arr[index][lableName]:undefined }else{ return undefined } }
应用
<template>
<div>
</div>
</template>
<script>
export default {
data() {
return {
list:[{
name:'张三',
id:'1'
},{
name:'李四',
id:'2'
},{
name:'王五',
id:'3'
}],
id:'1'
}
},
mounted(){
let name = this.getName(this.list,this.id,'id','name')
console.log(name)
},
methods: {
getName(arr,id,idName,lableName){ //通过id获取数组名称
if(id||id=='0'){
const index = arr.findIndex((role) => role[idName] === id)
return index>=0?arr[index][lableName]:undefined
}else{
return undefined
}
}
},
}
</script>
<style lang="scss" scoped>
</style>