我在开发应用程序时遇到问题。我用打字稿使用Vue + Vuetify,但我不想创建SPA应用程序或使用webpack来处理.vue组件,我需要创建多个页面,每次创建新的Vue实例。但是,当我创建例如Vue with TypeScript without components
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我不能叫this.getData()在(),但是当我在浏览器中调试我的代码时,我看到该对象“this”具有所有这些属性和方法。
我使用属性$ data [“property”] name和$ options.methods [“methodName”]为了使用它,但我明白这是不正确的做法。 我在Vue文档中阅读了有关ComponentOptions的文档,这些文档有助于创建界面或vue-class-component,但所有这些工具都使用组件,我想避免这些组件。
在这种情况下,我可以使用vue + typescript吗?我会很感激提示我的问题
数据不一定是主vue实例的函数。它只需要成为mixin和组件等功能的函数。 –
在这种情况下你的权利。您可以在单个实例上执行此操作,但不建议这样做。看到这个错误:'[Vue warn]:“data”选项应该是一个函数,它返回组件定义中的每个实例的值。或者这篇短文:https://vuejs.org/2016/02/06/common-gotchas/#Why-does-data-need-to-bea-a-function ...我会更新我的文章。 – Phil
当然,建议vue实例为数据属性而不是函数使用对象,实际上,没有一个示例创建vue实例的文档使用数据函数。参考:https://vuejs.org/v2/guide/instance.html您引用的[Vue警告]错误消息是关于组件。在组件中,使用函数返回数据非常重要,但这不适用于主vue实例。 –