Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

276
Views
Is it safe to pass a prop object to `ref()` for it to be modified?

In Vue 3, can I create a ref from a prop that is an object to modify in my component?

<template>
  <button @click.prevent="increment">You've clicked me {{ countObj.count }} times</button>
</template>

<script>
import { defineComponent, ref } from 'vue'

export default defineComponent({
  props: {
    startingCount: {
      type: Object,
      default: () => ({
        count: 0
      })
    }
  },

  setup (props) {
    const countObj = ref(props.startingCount)
    const increment = () => {
      countObj.value.count++
    }

    return {
      countObj,
      increment,
    }
  }
})
</script>

Would my prop also be modified when modifying countObj?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The short answer is YES! Both the prop startingCount and countObj will be modified.

What's more interesting, is that if the parent component passes a reactive object for startingCount prop then the reactive on parent will reactively change too! See it live


But this is considered a bad practice. You shouldn't modify props directly. From docs:

All props form a one-way-down binding between the child property and the parent one: when the parent property updates, it will flow down to the child, but not the other way around. This prevents child components from accidentally mutating the parent's state, which can make your app's data flow harder to understand.

In order to perform a mutation to the parent component you can emit an event.

Read more about One-way data flow including the use case of Mutating Object / Array Props.


In your case, in order to fix the prop mutation problem replace this:

const countObj = ref(props.startingCount)

with:

const countObj = ref({ count: props.startingCount.count })

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!