1

Is there any way using the new Vue.js Reactivity API to bind an object key to an existing Ref value as readonly?

Example.

setup() {
  const input = ref({
    firstName: 'Bob',
    email: '[email protected]'
  })

  const args = {
    postID: 32,
    email: readonly(input.value.email)
  }

  return { input, args }
}

This doesn't work.
args.email doesn't get updated.

0

2 Answers 2

3

As @boussadjra-brahim pointed out, readonly can't be used for nested fields.
Only workaround without copying the whole object might be using computed then.

const args = computed(() => {
  return {
    post_id: 32,
    email: input.value.email,
  }
})
Sign up to request clarification or add additional context in comments.

Comments

1

Readonly accepts a property created using ref or reactive not a nested field in that property in order to be reactive:

 const input = ref({
    firstName: 'Bob',
    email: '[email protected]'
  })

  const args =readonly(input)

2 Comments

I don't necessarily want to use readonly for the whole object in this situation. Using computed might be a better solution then I guess.
I just mentioned that, in this case readonly looks useless, it's recommended to use computed as you did since it's reactive and immutable

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.