4

How to reuse some existing ES6 classes in Vue Js.

Have a class which has a variable being updated by observable.

class A { 
    public a: string;
    someobservable.subscribe((a) =>{
         this.a = a;
    })
}

In vue.JS have created the object of this class.

Sample how property is been used:

created: {
    objA = new A();
}
methods: {
    getA() {
        if(this.objA !== undefined){
            return objA.a;
        }
    }
}

and in vue template:

<div>{{getA()}}</div>

The value in template gets out of sync with value of variable in class.

Is there any other way to use the property in Vue template that it keeps updating real time.

NAVIN
  • 3,193
  • 4
  • 19
  • 32

2 Answers2

3

It should work with getA() as a computed property rather than a method. Also, you can skip the if statement as no return statement will return undefined.

computed: {
  getA() {
    return objA.a;
  }
}
Richard Matsen
  • 20,671
  • 3
  • 43
  • 77
  • Hi using it in computed worked pretty well. Thanks. actually, we use typescript with Vue.extend so that condition was necessary. – SHUBHAM RAGHUWANSHI Oct 09 '18 at 18:40
  • Cheers, glad that works for you. I haven't used Typescript with Vue, but in Angular (for example) can usually type as `any` to circumvent TS-specific error messages. (So maybe `getA(): any {` gets around it). – Richard Matsen Oct 09 '18 at 23:25
2

You are creating the instance in the global scope. You need to instantiate your object in the data field for vue to be able to track any changes ..

data: {
    objA: new A();
},

Then you can either use a method like you did ..

methods: {
    getA() {
       return this.objA.a;
    }
},

<div>{{getA()}}</div>

Or use a computed property like others have said ..

computed: {
    getA() {
       return this.objA.a;
    }
}

<div>{{getA}}</div>

Both will have the same effect, but it's better to use a computed property to take advantage of the caching.

Husam Ibrahim
  • 6,999
  • 3
  • 16
  • 28