Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

34
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!

7 months 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>

7 months 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

7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos