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?
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 })