【问题标题】:Vue.js typescript interface not workingVue.js 打字稿界面不起作用
【发布时间】:2018-05-25 05:59:14
【问题描述】:

有谁知道在 vue.js 中为数据属性创建类型的语法是什么(应用程序是用 typescript 编写的)? 我正在寻找类似的东西:

@Component({
  data() {
    return {
      sections: Array<SomeInterface> = []
    }
  }
})

但是 vue 将类型视为一个值,我很困惑如何处理它。

【问题讨论】:

标签: javascript typescript vue.js


【解决方案1】:

您不能像通常在类型之前那样使用:,因为语法与JavaScript 的key: value 对象字面量语法冲突。您可以通过将空数组 [] 强制为 SomeInterface[] 类型来使用类型推断:

@Component({
  data() {
    return {
      sections: [] as SomeInterface[]
    }
  }
})

【讨论】:

  • 您应该考虑更深入地解释您的答案。它被标记为“低质量”,因为它主要是代码。
  • 我认为与 OP 的代码相比,无法详细解释。已更新。
  • 这正是我在这种组件中寻找的,但事实证明我应该使用不同的语法,非常感谢! +1
【解决方案2】:

您应该使用class-style componentsvue-class-component,这样您就可以将这些声明移至类属性并与Typescript 配合使用。

import Vue from 'vue'
import Component from 'vue-class-component'

// The @Component decorator indicates the class is a Vue component
@Component({
  // All component options are allowed in here
  template: '<button @click="onClick">Click!</button>'
})
export default class MyComponent extends Vue {
  // Initial data can be declared as instance properties
  message: string = 'Hello!'

  // Component methods can be declared as instance methods
  onClick (): void {
    window.alert(this.message)
  }
}

【讨论】:

    猜你喜欢
    • 2016-06-21
    • 2020-03-18
    • 1970-01-01
    • 2018-02-04
    • 2017-02-20
    • 2019-02-06
    • 1970-01-01
    • 2018-02-08
    • 2016-11-21
    相关资源
    最近更新 更多