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

167
Vistas
Vue 2: Set empty class as data property

I have a scenario in Vue 2 where I am initializing API classes as data properties on my component like so:

new Vue({
  el: '#my-element'
  data: {
    apiUrl: apiUrl,
    api: new ApiClient(this.apiUrl)
  }
})

API Client:

class ApiClient {
  constructor(apiUrl) {
    this.apiUrl = apiUrl;
  }

  async getRequest() {
    // Perform GET
  }
}

This works just fine, but I have scenarios where I need to use two different API clients. If a certain prop gets passed into my component, I want to initialize that data property as secondApi, as an example.

In this scenario, I see myself using the created() hook:

created() {
  if (prop === true) {
    this.secondApi = new SecondApiClient(this.apiUrl);
  }
}

In my data : { } object though, I'm not sure how to initialize this optional secondApi property properly (in the case that the prop is not passed in). Do I just set it as an empty object at first? It will always be a class object like apiClient. Is there an empty class data type?

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

0

Yes you can follow one of the below

Approach 1:

data() {
 return {
  apiUrl: apiUrl,
  api: null // or you can even keep it as new ApiClient(this.apiUrl) if that's the default value
 }
},
props: ['certainProperty'],
created() {
  if (this.certainProperty === true) { // certainProperty is a prop
    this.api = new SecondApiClient(this.apiUrl);
  } else this.api = new ApiClient(this.apiUrl);
}

Sometimes there might be a delay in receiving the props so its better to follow the below approach

Approach 2:

data() {
 return {
  apiUrl: apiUrl,
  api: null // or you can even keep it as new ApiClient(this.apiUrl) if that's the default value
 }
},
props: ['certainProperty'],
watch: {
 certainProperty(newVal) {
  if (newVal === true) { // certainProperty is a prop
    this.api = new SecondApiClient(this.apiUrl);
  } else this.api = new ApiClient(this.apiUrl);
 }
}

Note: You need to pass the props from parent component like

<child-component :certainProperty="true" />
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