Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!