Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

124
Vistas
Handling null properties within props used to v-model

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 back-end. 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!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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>

about 4 years ago · Juan Pablo Isaza Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda