[代码优化]有值时才显示

44 阅读1分钟

原代码:

<dl>
  <dt>门店概览</dt>
  <dd>
    <div>
      <van-row v-if="shopDetail.hospitalArea || shopDetail.operatingRooms">
        <van-col v-if="shopDetail.hospitalArea" span="12">
          门店面积: {{ shopDetail.hospitalArea }}
          m&sup2;
        </van-col>
        <van-col v-if="shopDetail.operatingRooms" span="12">手术室数量: {{ shopDetail.operatingRooms }}</van-col>
      </van-row>
      <van-row v-if="shopDetail.treatmentRooms">
        <van-col span="24">治疗室数量: {{ shopDetail.treatmentRooms }}</van-col>
      </van-row>
      <van-row>
        <p v-if="shopDetail.introduction">简介: {{ shopDetail.introduction }}</p>
      </van-row>
    </div>
  </dd>
</dl>

优化后:

<dl v-if="shopInfo.length">
  <dt>门店概览</dt>
  <dd>
    <div v-for="(row, index) in shopInfo" :key="index" class="flex">
      <span v-for="i in row" :key="i.key" class="flex1">
        <span>{{ i.label }}:</span>
        <span v-html="i.value"></span>
      </span>
    </div>
  </dd>
</dl>
get shopInfo() {
  const map: any = [
    [
      { key: "hospitalArea", label: "门店面积", suffix: "m&sup2;" },
      { key: "operatingRooms", label: "手术室数量", suffix: "" },
    ],
    [{ key: "treatmentRooms", label: "治疗室数量", suffix: "" }],
    [{ key: "introduction", label: "简介", suffix: "" }],
  ];
  map.forEach((item) => {
    item.forEach((i) => {
      const key = i.key;
      const value = this.shopDetail[key];
      if (value) {
        i.value = value + i.suffix;
      }
      return i;
    });
  });
  return map.filter((i) => i.some((i) => i.value));
}