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

476
Vistas
Vue js the field in data() was not initialized by call of second (help) function

I don't have almost any experience with vue js.

I have 2 functions loadComponentsOfUser() and loadUserId(), so that loadComponentsOfUser() uses the userID field, which must be loaded by the loadUserId() function.

data() {
  return { 
    userId: ''
  }
},

created() {
  this.loadComponentsOfUser()
},

methods(): {
   loadUserId() {
       axios.get('getUserId').then(res => {
            this.userId = res.data
        }).catch(() => {
            ...
            })
        });
     },
     loadComponentsOfUser() {
         this.loadUserId()
         axios.get('users/' + this.userId).then(res => {
         }).catch(() => {
             ...
             })
         });
}

The loadUserId() function works correctly and loads the correct value from the server

But when loadComponentsOfUser() is called, the this.userId field looks like it has not been initialized and an empty field comes to the axios.

my question is why the field was not initialized after calling loadUserId()?

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

0

You need to wait for responses, yo can use async and await:

new Vue({
  el: '#demo',
  data() {
    return { 
      id: 1,
      userId: '',
      user: null
    }
  },
  created() {
    this.loadComponentsOfUser()
  },
  methods: {
    async loadUserId() {
       await axios.get('https://jsonplaceholder.typicode.com/users/' + this.id)
         .then((res) => {
           this.userId = res.data.id
         })
         .catch(() => {})
    },
    async loadComponentsOfUser() {
      await this.loadUserId()
      if(this.userId) {
        axios.get('https://jsonplaceholder.typicode.com/users/' + this.userId)
          .then(res => {
            this.user = res.data
          })
          .catch(() => {})
      }
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
  <input type="number" v-model="id" /><button @click="loadComponentsOfUser">load</button>
  {{ user }}
</div>

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