I made a computed property to sort a Javascript object alphabetically by key. I added logging to the computed property to make sure that it was not being invoked without a dependency change.
I found that without changing the reactive dependency (sensorData), the computed property seems to reevaluate at a high rate (10+ Hz).
Why is it reevaluating without a dependency change?
I know that Vue recommends against property addition/deletion, and my object is initialized to {}. However, even when initializing it with every key, I had the same result.
I also tried vm.$set(object, key, value) as recommended if properties need to be added after a page is rendered. No luck.
{
"readings": {
"stepperC": 180,
"stepperA": 360,
"stepperB": 0
}
}
data: () => ({
sensorData: {}
}),
computed: {
// sort alphabetically by key
sortedSensorData() {
console.log("calling sort");
return Object.keys(this.sensorData).sort()
.reduce((obj, key) => ({
...obj,
[key]: this.sensorData[key]
}), {});
}
}
methods: {
handleWebSocketMessage({ data }) {
const newReadings = data.readings;
if (Object.entries(newReadings).some(([sensor, reading]) => this.sensorData[sensor] !== reading))
this.sensorData = newReadings;
}
}
With no change to sensorData:
calling sort
calling sort
calling sort
...