【问题标题】:Type checking a simple Vue.js app with TypeScript使用 TypeScript 对简单的 Vue.js 应用程序进行类型检查
【发布时间】:2017-09-09 10:37:18
【问题描述】:

Vue.js 带有官方 TypeScript 类型定义,这些定义与 NPM 一起安装在库中。

我正在尝试使用它们来键入检查一个简单的应用程序。我发现的所有示例都演示了在组件中使用 TypeScript,但我找不到一种方法来检查一个简单的应用程序,例如:

import * as Vue from 'vue';

interface Item {
    name: string;
}

var app = new Vue({
  el: '#app',
  data: {
    items: <Item[]> []
  },
  methods: {
    addItem: function () {
      this.items.push({ name: 'Item' });
    }
  }
});

我想主要的挑战是所有数据、方法、计算属性等都应该在this 上可用。但是在这种情况下,this 的类型为 Vue,并且不包含 items 属性。

有没有办法解决这个问题?

【问题讨论】:

    标签: typescript vue.js


    【解决方案1】:

    这样的东西可能会有所帮助,我对 VueJS 不太熟悉,但试试这个

    import * as Vue from 'vue';
    
    interface Item {
       name: string;
    }
    
    interface App extends Vue {
       items: Item[];
    }
    
    export default {
      el: '#app',
      data: {
        items: <Item[]> []
      },
      methods: {
        addItem: function () {
          this.items.push({ name: 'Item' });
        }
      }
    } as ComponentOptions<App>
    

    替代方法是使用对等依赖项

    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
      el: '#app' //... rest of your options
    })
    export default class Item extends Vue {
      // Initial data can be declared as instance properties
      items: <Item[]> []
      // Component methods can be declared as instance methods
      addItem (): void {
        this.items.push({name: 'Item' });
      }
    }
    

    【讨论】:

    • 谢谢!我必须调整第一个示例以使其正常工作(请参阅我的编辑)。但是,第二个对我不起作用。我没有要从中导入的“vue-class-component”模块,当我尝试import Component from 'vue' 时,编译器抱怨组件不可调用。
    • 是的,对于第二个示例,您需要 npm 安装它。第一个例子有一些缺点。
    猜你喜欢
    • 1970-01-01
    • 2018-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    • 2019-12-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多