遇到这种情况怎么写更优雅?
  <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函数,直接在这里写怎样才能写得更优雅
回答:
(sourceDataTypeOptions.find(x => x.value === row.sourceDataType)||{}).label||''
通用给默认值的写法
回答:
在数组接收并赋值的时候就提前转换好并且拼接上去,而不是在模版层(template)当中处理。
比如说
<template>  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="date" label="日期" />
    <el-table-column prop="name" label="姓名" />
    <el-table-column prop="address" label="地址" />
  </el-table>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      userList:[]
    }
  },
  methods:{
    loadData(){
      fetchTableData().then(res => {
        this.tableData = res.result.data.map(item => {
           const userInfo = this.userList.find(user => user.id === item.usr) || { name: '', address: '' }
           return { ...item, userName: user.name, userAddress: user.address }
        })
      })
    }
  }
}
</script>
或者通过 filter 来过滤,比如说
<template>  <el-table :data="tableData" style="width: 100%">
    <el-table-column prop="date" label="日期" />
    <el-table-column prop="name" label="姓名">
      <span slot-scope="{row}">{{ row | getRowUserInfo('name') }}</span> 
    </el-table-column>
    <el-table-column prop="address" label="地址">
      <span slot-scope="{row}">{{ row | getRowUserInfo('address') }}</span> 
    </el-table-column>
  </el-table>
</template>
<script>
export default {
  data() {
    return {
      tableData: [],
      userList:[]
    }
  },
  filters:{
  filters:{
    getRowUserInfo(row, field) {
      const userInfo = this.userList(user => user.id === row.usr) || {}
      return userInfo[field] || ''
    },
  }
}
</script>
但是其实还是推荐在一开始就把数据处理好(也就是第一种),以优化业务代码的性能。
回答:
在 script 里面写个method处理数据,不要在 template 里面.
回答:
{{sourceDataTypeOptions.include(row.sourceDataType) ?
          sourceDataTypeOptions.find(x => x.value === row.sourceDataType).label : ''}}以上是 遇到这种情况怎么写更优雅? 的全部内容, 来源链接: utcz.com/p/933320.html
