How can we efficiently trigger a costly recalculation only once for a computed value that depends on multiple references, where one reference is dependent on the other?
For example:
In the following scenario, I aim to compute expensiveData
only once. The value of expensiveData
gets recalculated when either varA
or varB
changes. However, varB
is derived from varA
, so any change in varA
will result in a change in varB
.
import { ref, watch } from '@vue/composition-api';
// Definition of varA, updated with fetched data changes
const varA = ref([
/* some data */
]);
// Definition of varB, derived from varA but independently modifiable
const varB = ref(null);
// Derive varB based on varA's value
const updateVarB = (a) => {
const varBValue = /* process varA */;
varB.value = varBValue
};
// Update varB when varA changes
watch(varA, (newVarA) => {
updateVarB(newVarA);
});
export { varA, varB, updateVarB }
some-other-file.js
...
// Change varB upon a user-triggered event
const someData = ...
updateVarB(someData);
expensive-calc.js
import { computed, toRefs } from '@vue/composition-api';
...
/* varA and varB are passed as props */
const { varA, varB } = toRefs(props);
const makeExpensiveData = (...args) => /* some heavy lifting */
const expensiveData = computed(() => {
/* Perform calculations with varA and varB */
return makeExpensiveData(varA.value, varB.value)
});
What strategies can be employed to ensure that expensiveData
is recomputed just once?
Key considerations:
varA
andvarB
have distinct meanings, making it unsuitable to create a single computed value combining them.
The current workaround involves debouncing the call to makeExpensiveData
using lodash.debounce
. As varB
is derived from varA
, they trigger reevaluation together.
However, being fairly new to Vue's composition API, I am curious about better solutions for addressing this issue.