And that works because unwrap is a sugar function for it checks if the variable is a ref. And if it is a ref, it returns, it calls count.value. Otherwise it just returns the value itself. If you're using VSCode and using the Volar extension, you can enable that it automatically adds.value to refs. This is a setting you can enable. It's called autocomplete-refs. It's disabled by default to reduce CPU usage.
And you can see in this example, if you hit, if you enter the name count, the extension automatically adds.value after the variable name, which can be quite handy.
Now let's do a comparison between reactive and ref. Ref scores as it can be used with any value in comparison to reactive that can only be used on object types. But there's a downside using ref, and that is because values are accessed differently in script and template. So this is a plus point for reactive. Because using ref inside the script tab, you need to call.value. But Vue automatically unwraps the ref in the template so you don't need to call.value there. Ref objects can be reassigned, which is a plus point for ref. Ref also scores because references can be passed across functions without losing reactivity. We also saw that reactive loses reactivity if we try to destructure object properties into local variables. But there's an advantage using reactive if you try to migrate to composition API because it's similar to view tools data object.
Let's come to the conclusion. My opinion, I prefer ref. And what I like most about ref is that you know that it's a reactive value if you see that it's property is accessed via .value. And it's not that easy if objects are created with reactive. So if you see this line of code in your application, you don't know if any object is a plain JavaScript object or if it is a reactive object. If you see this line inside your application, it's quite likely that any ref is a ref and behaves reactively.
Let's talk about a recommended pattern and that's grouping refs inside a reactive object. So we have two refs loading an error and we pass them into a reactive object which is assigned to a local state variable. We can now watch the whole reactive object using watch effect, but we can also define watchers for the refs separately. And what's nice about that, if we update the ref, for example, setting the loading value to false, this triggers both watchers. And if you don't need the reactivity of the state object, you can also group it in a plain JavaScript object. Grouping refs results in a single object which is easier to handle, keeps your code organized and at a glance, you can see that the grouped refs belong together and are somehow related.
Comments