Migrating From Durandal to Vue: Use shallowRefs Instead of refs When Replacing KnockoutJS Observables
When converting the application I'm working on from Durandal to Vue I had to learn the differences between how Knockout and Vue handle reactivity. This doesn't apply to all instances but it is something to consider when converting objects that contain KnockoutJS observables.
In Vue, state is deeply reactive by default. This means you can expect changes to be detected even when you mutate nested objects or arrays
This raised an issue as some of the objects in the application are large and only certain members need to be reactive. Converting the ko.observable to ref would not be suitable in this case because it could cause problems with performance.
As you can see the only ref in the component is refForComponent but I can update the values in the nested objects using the buttons and the values are updated in the UI.
Vue does provide an escape hatch to opt-out of deep reactivity by using shallowRef() and shallowReactive(). Shallow APIs create state that is reactive only at the root level, and exposes all nested objects untouched. This keeps nested property access fast, with the trade-off being that we must now treat all nested objects as immutable, and updates can only be triggered by replacing the root state
This is similar behaviour to Knockout observables. So when updating code I changed ko.observable to shallowRef and then when the value was being changed/read I used the .value property of Vue instead of the function call of Knockout.
So far, so good. I'll try to update this post if I run into any relevant issues in the future.
Comments ()