sunalive
sunalive

Reputation: 285

Vue class component can't access data properties from constructor

I'm trying to use Vue with typescript but am getting an error, saying that my member variable is undefined.

import { Component, Vue, Prop } from 'vue-property-decorator';
import UploadApi from './UploadApi';
import ApiConfig from '../../api/api.config';

@Component
export default class UploadCard extends Vue {
  uploading = false;

  private uploads: Array<Upload> = [];

  private api: UploadApi = new UploadApi(ApiConfig.get());

  constructor() {
    super();
    this.getUploads();
  }

  private getUploads() {
    // const loading = this.$store.state.vs.loading();
    // mimic http request
    console.log(this.$data);
    console.log(this.uploading);
    this.api.getUploads().then((response) => {
      console.log(response);
    });

Here for example it is saying this.api is undefined, does anyone know about this?

Upvotes: 1

Views: 946

Answers (1)

Noah Stahl
Noah Stahl

Reputation: 7553

Rather than using a constructor, use the lifecycle methods to do setup tasks. For example, replace your constructor with created or mounted:

created() {
    this.getUploads();
}

Please see the docs for more details.

Upvotes: 1

Related Questions