随便记录一下
主要是通过计算属性来简化和优化代码。在 Vue 中,计算属性是一种方便的工具,可以让你根据依赖状态的变化来动态计算衍生值。在这个例子中,我们使用计算属性
formattedCommunicationType
来根据workDetail.realTimeItemDeviceDTO.communicationType
的值动态计算通信类型的显示文本,从而避免了重复的逻辑和代码。通过使用计算属性,我们能够更清晰地表达代码的意图,并且在需要时自动更新计算结果。这样可以提高代码的可读性和可维护性,同时减少重复代码的使用。
旧代码
<div class="mode-top">
<span
v-if="
workDetail.realTimeItemDeviceDTO.communicationType &&
workDetail.realTimeItemDeviceDTO.communicationType == '4G'
"
>
{{
workDetail.realTimeItemDeviceDTO.communicationType
? workDetail.realTimeItemDeviceDTO.communicationType
: '--'
}}
</span>
<span
style="font-size: 10px"
v-else-if="
workDetail.realTimeItemDeviceDTO.communicationType &&
workDetail.realTimeItemDeviceDTO.communicationType == 'WIFi'
"
>
{{
workDetail.realTimeItemDeviceDTO.communicationType
? workDetail.realTimeItemDeviceDTO.communicationType
: '--'
}}
</span>
<span
v-else-if="
workDetail.realTimeItemDeviceDTO.communicationType &&
workDetail.realTimeItemDeviceDTO.communicationType == 'Lan'
"
>
{{
workDetail.realTimeItemDeviceDTO.communicationType
? workDetail.realTimeItemDeviceDTO.communicationType
: '--'
}}
</span>
<span
v-else-if="
workDetail.realTimeItemDeviceDTO.communicationType &&
workDetail.realTimeItemDeviceDTO.communicationType == 'Nb_lot'
"
>
{{
workDetail.realTimeItemDeviceDTO.communicationType
? workDetail.realTimeItemDeviceDTO.communicationType.slice(0, 2)
: '--'
}}
</span>
<span v-else> -- </span>
</div>
这样写是因为刚开始它嵌套没有这么多,直接.xxx就可以拿到,现在是.realTimeItemDeviceDTO.xxx才能拿到,并且刚开始不知道它会有多种通讯模式,加上ui设计,它设计是这样的,如果字数太多还要截取的情况,就太繁琐,要改,
新代码,这样就好了
const communicationTypes: Record<string, string> = {
'4G': '4G',
WiFi: 'WIFI',
Lan: 'Lan',
Nb_lot: 'Nb',
};
const formattedCommunicationType = computed(() => {
const type = workDetail.value.realTimeItemDeviceDTO?.communicationType;
return type ? communicationTypes[type] || '--' : '--';
});
<div class="mode-top">
<span style="font-size: 10px">{{ formattedCommunicationType }}</span>
</div>