2017-04-13 61 views
1

Vue.js附帶正式的TypeScript類型定義,它們隨着NPM一起安裝在庫中。使用TypeScript檢查簡單的Vue.js應用程序類型

我想用它們鍵入檢查一個簡單的應用程序。所有我發現展示的組件使用打字稿,但我無法找到一個方法來輸入檢查簡單的應用程序,如樣品:

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屬性。

有沒有辦法解決這個問題?

回答

2

像這樣的事情也許會有幫助,我不是太熟悉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' }); 
    } 
} 
+0

謝謝!我不得不調整第一個例子,使其工作(請參閱我的編輯)。但是,第二個沒有爲我工作。我沒有'vue-class-component'模塊來導入,當我嘗試從'vue'導入Component時,編譯器會抱怨Component不可調用。 –

+0

對於第二個例子,你需要npm安裝它。第一個例子有一些缺點。 – Byrd