I get props from parent with
const props = defineProps<{
customer: Customer
}>()
Then I am const assigning to vModel, to be able to write/change data since props are read only.
model = useVModel(props, 'customer')
then on form I am using
<input v-model="model.name" type="text" />
All i want is to modify data from props and put
them to api.
Simple crud. Edit:
Because I cant :
<input v-model="model.name" :value="model.name" type="text" />
I want to populate form via Props, then update them via v-model
I am trying to figure out, how to create a crud and pass props to modal for edit.
EDIT 2:
i tried add to ref()
let formData = ref({
customer: {
name: props.customer.name,
department: props.customer.department,
},
})
so I can use
<input v-model="formdata.customer.name" type="text" />
but I get:
EditCustomer.vue:66 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'name')
CodePudding user response:
Props can't be modified shallowly like props.foo =
, and shouldn't be modified deeply like props.foo.bar =
. The only suitable way is to send an event to parent component where a value that is passed through a prop exists, so it could modify it for a child. This is what v-model
does.
There's no way how useVModel(props, 'foo')
function could be written to work like that, because the arguments it's provided with only allow to modify props.foo
, which is readonly. In order to make it work, useVModel
needs to implement two-way binding, so an event with updated value could be changed in a parent, so it needs to be able to send events. This is what the documentation lists:
const data = useVModel(props, 'data', emit)
console.log(data.value) // props.data
data.value = 'foo' // emit('update:data', 'foo')
The example with ref
won't work because props.customer.name
is accessed directly inside setup function, this breaks the reactivity and also results in an error in case props.customer === undefined
at this moment.