Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

478
Visualizações
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 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!

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

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>

over 4 years ago · Santiago Trujillo Relatório

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

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda