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

166
Visualizações
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 Respostas
Responde à pergunta

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