【问题标题】:how to reuse es6 class in vue js?如何在 vue js 中重用 es6 类?
【发布时间】:2019-03-13 12:07:55
【问题描述】:

如何在 Vue Js 中重用一些现有的 ES6 类。

有一个类,它有一个被 observable 更新的变量。

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

在vue.JS中已经创建了这个类的对象。

如何使用属性示例:

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

在vue模板中:

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

模板中的值与类中变量的值不同步。

有没有其他方法可以使用Vue模板中不断实时更新的属性。

【问题讨论】:

  • 使用计算属性

标签: javascript vue.js ecmascript-6 ecmascript-2017


【解决方案1】:

您正在全局范围内创建实例。您需要在 data 字段中实例化您的对象,以便 vue 能够跟踪任何更改..

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

然后你可以像你一样使用一种方法..

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

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

或者像其他人所说的那样使用计算属性..

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

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

两者的效果相同,但最好使用计算属性来利用缓存。

【讨论】:

  • 这两种解决方案都非常好并且有效。我无法在数据中创建它,因为对象创建取决于其他东西。谢谢。
【解决方案2】:

它应该使用getA() 作为计算属性而不是方法。此外,您可以跳过 if 语句,因为没有 return 语句将返回 undefined

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

【讨论】:

  • 嗨,在计算中使用它效果很好。谢谢。实际上,我们使用带有 Vue.extend 的 typescript,所以这个条件是必要的。
  • 干杯,很高兴这对你有用。我没有在 Vue 中使用过 Typescript,但在 Angular(例如)中,通常可以键入 any 来规避特定于 TS 的错误消息。 (所以也许getA(): any { 绕过它)。
猜你喜欢
  • 2018-05-17
  • 2019-03-23
  • 2021-05-04
  • 2019-01-08
  • 2021-07-19
  • 2018-08-29
  • 2016-10-31
  • 2017-10-27
  • 1970-01-01
相关资源
最近更新 更多