Otter
Otter

Reputation: 270

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?

Upvotes: 2

Views: 1056

Answers (1)

Amaarockz
Amaarockz

Reputation: 4684

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

Upvotes: 1

Related Questions