[英]Vue with TypeScript without components
開發應用程序時遇到問題。 我將Vue + Vuetify與Typescript一起使用,但是我不想創建SPA應用程序或將Webpack用於.vue組件,因此我需要創建多個頁面,每次都在其中創建新的Vue實例。 但是當我創建例如
import * as Vue from 'Vue';
import axios from 'axios';
<any>window.vue = new Vue({
el: "#app",
data: {
drawer: true,
mini: false,
totalItems: 0,
items: [],
headers: [,
{
text: 'Dessert (100g serving)',
align: 'left',
sortable: false,
value: 'name'
},
{ text: 'Calories', value: 'calories' },
{ text: 'Fat (g)', value: 'fat' },
],
},
methods: {
getData() {
axios.get("http://exmaple1234.com/api/list")
.then((response) => {
this.$data["totalItems"] = 1;
this.$data["items"] = [
{
value: false,
name: 'Frozen Yogurt',
calories: 159,
fat: 6.0,
}
];
})
}
},
mounted() {
this.$options.methods["getData"].call("getData");
},
});
我的tsconfig.json
{
"compilerOptions": {
"alwaysStrict": true,
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": true,
"sourceMap": false,
"target": "es5",
"moduleResolution": "node",
"allowSyntheticDefaultImports": true,
"lib": [ "es2017", "dom", "dom.iterable" ]
},
"exclude": [
"node_modules"
],
"compileOnSave": true
}
使用打字稿,我不能使用this.totalItems,this.items,也不能在mount()中調用this.getData(),但是當我在瀏覽器中調試代碼時,我看到對象“ this”具有所有這些屬性和方法。
我使用屬性$ data [“ property”] name和$ options.methods [“ methodName”]來使用它,但是我知道這是不正確的方法。 我在Vue文檔中閱讀了有關ComponentOptions的信息,這些元素有助於創建接口或vue-class-component,但是所有這些工具都使用了組件,我想避免這些組件。
在這種情況下可以使用vue +打字稿嗎? 我很樂意回答我的問題的技巧
我添加了一個接口來描述所有數據屬性和方法。 添加this.getData();
/ this.$options.methods["getData"].call(this);
並創建了一個新的vue實例。
import * as Vue from 'Vue';
import axios from 'axios';
interface AppInterface extends Vue {
drawer: boolean,
mini: boolean,
totalItems: number,
items: any,
headers: any,
getData (): void
}
var App = {
el: "#app",
data: {
drawer: true,
mini: false,
totalItems: 0,
items: [],
headers: [{
text: 'Dessert (100g serving)',
align: 'left',
sortable: false,
value: 'name'
}, {
text: 'Calories',
value: 'calories'
}, {
text: 'Fat (g)',
value: 'fat'
}
]
},
methods: {
getData() {
axios
.get("http://exmaple1234.com/api/list")
.then((response) => {
this.$data["totalItems"] = 1;
this.$data["items"] = [
{
value: false,
name: 'Frozen Yogurt',
calories: 159,
fat: 6.0
}
];
})
}
},
mounted() {
// or this.$options.methods["getData"].call(this);
this.getData();
}
} as Vue.ComponentOptions<AppInterface>
// new vue instance
new Vue(App);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.