I am building a simple edit component in which the object to be edited is assigned as a prop of the component.
For example:
export default {
name: "EditPersonModal",
props: {
person: {},
}
...
}
A person
object contains an address
object, which in turn contains city
, state
, zip
, etc.
Within the component, it is not possible to model the address fields wth v-model="person.address.city"
as person.address
is null.
One solution to this is to check person.address
on creation, and set to {}
if it is undefined, however this results in the empty property making its way to the backend. Obviously, I could check for this, and null the property prior to any further processing but is there a cleaner was of doing this that doesn't involve checking each of a child object fields?
The same issue is also faced on an Add component
Thanks!
CodePudding user response:
Like @TrietDoan commented, you should avoid mutating props directly in child component. Instead of v-model
, just use :value
and then use optional chaining:
Vue.component('Child', {
template: `
<textarea :value="person.address?.city ?? ''" @input="$emit('input', $event.target.value)"></textarea>
`,
props: {
person: {},
}
})
new Vue({
el: '#demo',
data() {
return {
item: {name: 'pers', address: {city: 'city'}},
}
},
methods: {
updateCity(city) {
this.item.address.city = city
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<p>{{ item.address.city }}</p>
<Child :person="item" @input="updateCity" />
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
You could use optional chaining:
v-model="person.address?.city ?? ''"
person.address?.city
mean that if person.address
is null
or undefined
it return null
.
The ??
operator return the result on the right if the left-hand operator is null