I've been using Vue for about 7 years now but am new to the Vue 3 Composition API.
I am having an issue with a prop value being undefined
when trying to access it in a ref
object.
Parent component:
<template>
<NewTermsModal :company-id="companyId"></NewTermsModal>
</template>
<script setup>
import { ref } from 'vue';
const { companyId } = defineProps({
companyId: {
type: Number,
required: true
}
});
</script>
companyId
in the parent component is also a passed in prop and is populated with the correct id.
Child Component (NewTermsModal.vue)
<script setup>
import { ref } from 'vue';
const { show, companyId } = defineProps({
show: {
type: Boolean,
required: true,
default: false
},
companyId: {
type: Number,
required: true
}
});
var form = new ref({
name: null,
companyId: companyId
});
async function createNewTerms() {
console.log(form.value.companyId); // THIS IS UNDEFINED
});
</script>
In the child component function createNewTerms()
, form.value.companyId
is undefined
. However, if I log the value of the prop itself console.log(companyId)
it contains the correct value.
I'm not sure why my reactive form object is not updating with the prop value. Any help or guidance would be appreciated.
When you destructure props they are compiled like that (Vue 3.5+)
const test = ref({
companyId: __props.companyId
});
So the __props.companyId
expression is reactive, but when you assign it like you do, you assign the raw value and the reactivity is lost.
The reactivity is lost in Vue3.4- too since the destructured props are just raw values.
Use another way to preserve the reactivity like computed
as shown here: Playground