To refactor this code, we can focus on the following:
- Improving readability by adding documentation and simplifying complex expressions.
- Handling reactivity and computed values more efficiently.
- DRY (Don't Repeat Yourself) principle: Extract repetitive logic into separate functions or use existing Vue features.
- Enhancing the template for clarity and maintenance.
Here is a refactored version of the code with comments to guide through the changes:
<template>
<div class="station">
<button class="station__save" @click="saveStation">
<save-icon />
</button>
<dl class="station__info">
<dt class="station__uuid" @click="copyUuidToClipboard">{{ station.uuid }}</dt>
<div class="station__train train">
<div class="train__name">
<train-icon v-if="isTrainPresent" />
<div class="train__info">
<p v-if="isTrainPresent">
{{ station.info.train_name }}
</p>
<p v-else-if="isTrainEnroute">Enroute</p>
<p v-else>Not present</p>
</div>
</div>
<div class="station__controls" v-if="isTrainPresent">
<dd class="station__change">
<input type="text" v-model="stationName" />
<change-icon />
</dd>
<arrow-icon />
<select class="station__select" v-model="selectedStation">
<option disabled value="">Выбрать станцию</option>
<option v-for="stationOption in routeStations" :value="stationOption.uuid" :key="stationOption.uuid">
{{ stationOption.name }}
</option>
</select>
</div>
<div class="train__checkbox" v-if="isTrainPresent">
<label :for="`twoWay-${station.uuid}`">В две стороны?</label>
<input type="checkbox" :id="`twoWay-${station.uuid}`" v-model="twoWay" />
</div>
</div>
<button @click="goToStation" v-if="isTrainPresent">Go</button>
</dl>
</div>
</template>
<script setup>
import saveIcon from '@/shared/icon/saveIcon.vue'
import changeIcon from '@/shared/icon/changeIcon.vue'
import trainIcon from '@/shared/icon/trainIcon.vue'
import arrowIcon from '@/shared/icon/arrowIcon.vue'
import Button from '@/shared/button/Button.vue'
import { api } from '@/app/api'
import { ref, watchEffect } from 'vue'
import { useClipboard } from '@vueuse/core'
import { useStationStore } from '@/app/store/stationStore'
const props = defineProps({
station: {
type: Object,
default: () => ({})
}
})
// Refactor: Use watchEffect for efficiency
watchEffect(() => {
stationName.value = props.station.info?.station_name || '';
uuidCopy.value = props.station.uuid;
});
const stationStore = useStationStore()
// Refactor: Extracted functions to simplify template logic
const isTrainPresent = computed(() => props.station.info?.train_present)
const isTrainEnroute = computed(() => !isTrainPresent.value && props.station.info?.train_enroute)
const stationName = ref('')
const selectedStation = ref('')
const twoWay = ref(false)
const routeStations = computed(() => {
return stationStore.stations.filter(({ uuid, info }) => {
return info && uuid !== props.station.uuid && !info.train_present && !info.train_enroute
})
})
// Refactor:Use the Clipboard API instead of a separate ref variable
const { copy } = useClipboard()
function saveStation() {
// Use async/await for readability and try-catch for error handling
try {
console.log(props.station.uuid, stationName.value)
await api.setStationName(props.station.uuid, stationName.value)
console.log(`Имя станции сохранено`)
} catch (error) {
console.log(`Ошибка сохранения имени станции на имя ${stationName.value}. uuid:${props.station.uuid}`, error)
}
}
function goToStation() {
if (!selectedStation.value) return;
try {
console.log(`Пришло: uuid:${props.station.uuid}, select:${selectedStation.value}`)
await api.setStationSchedule(props.station.uuid, selectedStation.value, twoWay.value)
selectedStation.value = ''
console.log(`Станция ${props.station.name} uuid:${props.station.uuid}. Отправлена на ${selectedStation.value}. В две стороны? ${twoWay.value}`)
} catch (error) {
console.log(`Ошибка отправки на станцию`, error)
}
}
function copyUuidToClipboard() {
copy(props.station.uuid)
}
</script>
Changes made:
- Improved naming for readability and to reflect the operation, like
copyUuidToClipboard.
- Made use of
computed properties to handle conditional rendering logic.
- Simplified the Vue template by removing implicit conditions and improving the use of directives such as
v-if.
- Removed the individual
ref for uuidCopy and used the copy method directly with props.station.uuid.
- Used
watchEffect to reactively handle changes to stationName and uuidCopy when the station's information changes, instead of a manual watch.
- Improved error handling with consistent console logging in
saveStation and goToStation functions.
Please note that you should have corresponding icons and components available in your project since they weren't detailed in the initial code, such as saveIcon, changeIcon, etc. Also, the import of Button was not being used in the template and has been replaced with a native <button> element for clarity. If there's a specific need for the Button component, feel free to reintroduce it as necessary.