Search code examples
vue.jsvuejs3

Vue: different ways to get reactive value


I'm a bit confused about so many different ways of getting reactive value. What's the difference between prop.value, unref(prop) and toValue(prop)? When should I use which method?


Solution

  • Check the API docs page for any VueJS specific method and understand the differences:

    Returns the inner value if the argument is a ref, otherwise return the argument itself. This is a sugar function for val = isRef(val) ? val.value : val

    In other words, it is some simple function that returns a value if you variable is either a ref or an actual simple vanilla JS value


    Normalizes values / refs / getters to values. This is similar to unref(), except that it also normalizes getters. If the argument is a getter, it will be invoked and its return value will be returned.

    This is adding getters to the mix, so that you need to make even less of a check.


    • .value is the usual access thing where you need to use it on a ref only, no point in using it on a string, object or anything in vanilla JS.

    So .value is the most restrictive and harder one to use, because you need to care about what you use it on. The other ones are mostly useful wrapper methods that you could use on a lot of things to ignore their specific ways of accessing a value.

    Check the linked pages for each of the methods for details.