You have the option to substitute watch
and data
with computed
, which essentially combines both functionalities into one. By default, computed
only has a getter, but you can also include a setter.
I've enhanced your code for better efficiency. Essentially, you only require the base unit (let's say Kelvin
), and then perform operations based on this unit while adjusting other units whenever any change is made.
Here is the functional code (snippet on codesandbox.io):
<template>
<div id="temperatureList">
<label for="decimalTemp">Decimal Places </label>
<input
class="decimals"
type="number"
min="0"
max="10"
step="1"
v-model="decimalTemp"
/>
<table>
<tr>
<td>
<input
id="kelvinIn"
type="number"
min="0"
step="1"
v-model="Kelvin"
/>
</td>
<td>Kelvin (K)</td>
</tr>
<tr>
<td><input id="celsiusIn" type="number" v-model="Celsius" /></td>
<td><label for="celsiusIn">Celsius (ºC)</label></td>
</tr>
<tr>
<td><input id="farenheitIn" type="number" v-model="Fahrenheit" /></td>
<td><label for="farenheitIn">Farenheit (ºF)</label></td>
</tr>
<tr>
<td><input id="newtonIn" type="number" v-model="Newton" /></td>
<td><label for="newtonIn">Newton (ºN)</label></td>
</tr>
</table>
</div>
</template>
<script>
export default {
name: "Temperature",
data: () => ({
decimalTemp: 0,
baseInKelvins: 293.15,
}),
computed: {
Kelvin: {
get: function () {
return this.baseInKelvins.toFixed(this.decimalTemp);
},
set: function (newVal) {
this.baseInKelvins = +newVal;
},
},
Celsius: {
get: function () {
return this.fromKelvin()
.Celsius(this.baseInKelvins)
.toFixed(this.decimalTemp);
},
set: function (newVal) {
this.baseInKelvins = this.toKelvin().Celsius(+newVal);
},
},
Fahrenheit: {
get: function () {
return this.fromKelvin()
.Fahrenheit(this.baseInKelvins)
.toFixed(this.decimalTemp);
},
set: function (newVal) {
this.baseInKelvins = this.toKelvin().Fahrenheit(+newVal);
},
},
Newton: {
get: function () {
return this.fromKelvin()
.Newton(this.baseInKelvins)
.toFixed(this.decimalTemp);
},
set: function (newVal) {
this.baseInKelvins = this.toKelvin().Newton(+newVal);
},
},
},
methods: {
fromKelvin: () => ({
Celsius: (t) => t - 273.15,
Fahrenheit: (t) => 1.8 * t - 459.67,
Newton: (t) => ((t - 273.15) * 33) / 100
}),
toKelvin: () => ({
Celsius: (t) => t + 273.15,
Fahrenheit: (t) => (t + 459.67) / 1.8,
Newton: (t) => (t * 100) / 33 + 273.15
}),
},
};
</script>
<style scoped>
table {
margin: 0 auto;
}
table tr td {
text-align: left;
}
input {
text-align: right;
}
</style>