computed refresh too often
-
ok, found this: https://flaviocopes.com/vue-watchers/
now the question is whether this is the good practice for this kind of scenario, thanks -
The only difference between watchers and computeds is computeds are cached. And since this is waiting for an update from a server anyway and it isn’t a huge calculation, a watcher should be fine.
Scott
-
The watcher works great but… Is there a way to watch 2 properties?
I have 3 functions (Y changes immediately so no need to watch it)
1 use X and Y
2 use X
3 use X and Z1 and 2 can happen by watching X
but 3 should happen by watching X and Z because sometimes X returned first and sometimes Z.
How can this be done?
Thanks -
Reacting to two props would need a computed property.
Scott
-
but it will bring me back to square 1 where a change on each property will trigger the computed calculation.
Maybe I will move this part to the server as well. -
@amoss Watch as many properties as you need to. Calculate your display number which isn’t watched or computed with a function.
https://codepen.io/turigeza/pen/MWwOYZE?editors=1010 -
I’m watching the 2 props
watch: { prop1: function() { this.getCalc(); }, prop2: function() { this.getCalc(); } }, getCalc() { this.calc = prop1 / prop2 * 100; },
This works but it works twice, once when prop1 is being updated and once when prop2 is being updated so there’s a short flickering on the screen with a wrong number.
I need both props to be updated and only then, call getCalc.
Thanks -
@amoss There is no built in method to achieve that you have to track changes to those variables yourself.
If you only truly want to recalculate when both changed then you should have fields like prop1Tainted, prop2Tainted and mark those tainted with your watchers. Only recalculate if they are both tainted / changed.
But if you are just worried about the flickering you should debounce your recalculate function.
-
English please
What do you mean by “you should debounce your recalculate function”? -
@amoss It is english : ))
Look at Lodash docs …
https://lodash.com/docs/4.17.15#debounce
Or
https://davidwalsh.name/javascript-debounce-functionBasically you don’t react to changes immediately but wait x milliseconds to see if any other action happened which effects the outcome.
Typically you use it when users type in a textfield you don’t go and react to every single keystroke but wait for a 250 millisecond silence/nonactivity only then would you go and save the field to the server or do what ever you need to.
-
Thanks, will check that