问题
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