Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda