Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

278
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda