how to reuse es6 class in vue js?

雨燕双飞 提交于 2021-02-07 08:15:23

问题


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.


回答1:


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



回答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.



来源:https://stackoverflow.com/questions/52708719/how-to-reuse-es6-class-in-vue-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!