Subscribe on changes!

Implement `valueOf` method to `Ref` for convenience.

avatar
Sep 12th 2021

What problem does this feature solve?

For reactivity, the composition api should define data variables by wrapping the value with ref or reactive, and use it with refer to the .value getter like unref function or variable.value.

This can sometimes require unnecessarily long code or cause confusion.

E.g)

const value = ref(0)
value.value++

or

const input = ref<HTMLInputElement>(null)
onMounted(() => {
  console.log(input.value.value)
})

According to the specification, a JavaScript standard object can have a valueOf method. it can be explicitly called or automatically converted to a primitive object when an object is accessed.

@see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/valueOf

It can simplify problems in many case:

const two = ref<number>(2)
const tenTimes = ref<number>(two * 10)
console.log(tenTimes)

What does the proposed API look like?

just add valueOf method that returns primitive value to Ref object

export interface Ref<T = any> {
  value: T
  [RefSymbol]: true
  _shallow?: boolean
  valueOf? : () => T
}
avatar
Sep 12th 2021

I think this was discussed in the RFC about composition api. Basically this would make the usage of refs very inconsistent, harder ton read, and harder to type