typescript 解决“类型 'Vue' 上不存在属性”错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45555089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Resolve "Property does not exist on type 'Vue'" error
提问by Tim Hutchison
I am using Typescript with Vuejs to build an application. I have several stand alone components (.vue) files that I am importing into a Typescript (.ts) file. In the Typescript file, I am importing Vue from the npm Vue library and then creating a new Vue to display my components. The error that I am seeing is:
我正在使用 Typescript 和 Vuejs 来构建应用程序。我有几个独立的组件 (.vue) 文件,我将它们导入到 Typescript (.ts) 文件中。在 Typescript 文件中,我从 npm Vue 库中导入 Vue,然后创建一个新的 Vue 来显示我的组件。我看到的错误是:
Property x does not exist on type 'Vue'
“Vue”类型上不存在属性 x
My build system is Webpack with tsc. Why am I getting this error and how can I resolve it?
我的构建系统是带有 tsc 的 Webpack。为什么我会收到此错误,我该如何解决?
main.ts
主文件
import Vue from 'vue';
import Competency from '../components/competency.vue';
new Vue({
el: "#app",
components: {
'competency': Competency
},
data:{
count: 0
},
methods:{
initialize: function(){
this.count = count + 1; // Errors here with Property count does not exist on type vue
}
}
})
tsconfig
配置文件
{
"compilerOptions": {
// "allowJs": true,
"allowSyntheticDefaultImports": true,
"experimentalDecorators": true,
"lib": [
"es2015",
"dom",
"es2015.promise"
],
"module": "es2015",
"moduleResolution": "node",
"noEmitOnError": true,
"noImplicitAny": false,
//"outDir": "./build/",
"removeComments": false,
"sourceMap": true,
"target": "es5"
},
"exclude": [
"./node_modules",
"wwwroot",
"./Model"
],
"include": [
"./CCSEQ",
"./WebResources"
]
}
webpack.config.js
webpack.config.js
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: {
Evaluations: './WebResources/js/main.ts'
},
devServer: {
contentBase: './dist'
},
module: {
rules: [{
test: /\.ts$/,
exclude: /node_modules|vue\/src/,
loader: 'ts-loader',
exclude: /node_modules/,
options: {
appendTsSuffixTo: [/\.vue$/]
}
},
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
esModule: true
}
},
{
test: /\.css$/,
use: [
'style-loader',
'css-loader'
]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: [
'file-loader'
]
},
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
alias: {
'vue$': 'vue/dist/vue.esm.js'
}
},
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
filename: 'Evaluations.html',
template: './WebResources/html/Evaluations.html'
}), new HtmlWebpackPlugin({
filename: 'ExpenseUpload.html',
template: './WebResources/html/ExpenseUpload.html'
}), new webpack.optimize.CommonsChunkPlugin({
name: 'WebAPI'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist')
}
}
采纳答案by may
you should make a declare for import *.vue file.
您应该声明导入 *.vue 文件。
such as:
如:
vue-file-import.d.ts
vue-file-import.d.ts
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
回答by reggaeguitar
I was trying to follow this page https://vuejs.org/v2/guide/routing.htmland was getting the same TypeScript errors, I fixed it by casting the Vue instance to type any like this
我试图关注这个页面https://vuejs.org/v2/guide/routing.html并且遇到了相同的 TypeScript 错误,我通过将 Vue 实例转换为任何这样的类型来修复它
new Vue({
el: '#app',
data: {
currentRoute: window.location.pathname
},
computed: {
ViewComponent() {
return routes[(this as any).currentRoute] || routes['/']
}
},
render (h) { return h((this as any).ViewComponent) }
})
回答by ArniqueMK
I got the same errors with vue 2.8.2 and Typescript 2.5.3. I fixed it by holding my Vue instance in a variable then giving it a type. This ensures TS will know about all Vue properties when you instatiate it using an options object.
我在 vue 2.8.2 和 Typescript 2.5.3 上遇到了同样的错误。我通过将我的 Vue 实例保存在一个变量中然后给它一个类型来修复它。这确保 TS 在您使用选项对象实例化它时将了解所有 Vue 属性。
var VueApp: any = Vue;
var App = new VueApp({
el: "#app",
data() {
return {
count: 0
}
},
methods:{
initialize() {
this.count = count + 1; // Should work now
}
}
})
回答by Eureka
Adding another answer to bring together several things you may need to fix.
添加另一个答案以将您可能需要修复的几件事情汇总在一起。
Ensure you include the ".vue" extension in the filename being imported
确保在导入的文件名中包含“.vue”扩展名
While both
虽然两者
import Competency from '../components/competency';
and
和
import Competency from '../components/competency.vue';
may compilesuccessfully, the second one will help avoid the error appearing in some IDE's such as VS Code.
可能编译成功,第二个将有助于避免出现在某些 IDE 中,例如 VS Code 中的错误。
Add a shim typings file
添加一个 shim 类型文件
As @May pointed out above, you need a file that imports and re-exports the type of "Vue". In @May's answer, it is named vue-file-import.d.ts, but elsewhere on the internet it is commonly called vue-shim.d.ts. Regardless of name, the content needed is the same:
正如@May 上面指出的,您需要一个导入和重新导出“Vue”类型的文件。在@May 的回答中,它被命名为 vue-file-import.d.ts,但在互联网的其他地方,它通常被称为 vue-shim.d.ts。无论名称如何,所需的内容都是一样的:
// vue-file-import.d.ts
declare module "*.vue" {
import Vue from "vue";
export default Vue;
}
Try different locations for the shim file.
为 shim 文件尝试不同的位置。
Originally I put it in "/src". I found this had an odd effect. Sometimes it worked, i.e. the VS Code error messages disappeared; and other times it didn't, they reappeared. This happened dynamically as I moved around the project editing different files.
最初我把它放在“/src”中。我发现这有一个奇怪的效果。有时它会起作用,即 VS Code 错误消息消失了;其他时候没有,它们又出现了。当我在项目中移动编辑不同的文件时,这是动态发生的。
I later found the suggestion for a shim file of identical content, but to be placed in "/typings". I tried this and it worked consistently. Other people seem quite happy with the "/src" location.
后来我发现建议使用相同内容的 shim 文件,但将其放置在“/typings”中。我试过这个,它一直有效。其他人似乎对“/src”位置很满意。
回答by Avraham Appel
Try using Typescript's generics. See https://www.typescriptlang.org/docs/handbook/generics.html
尝试使用 Typescript 的泛型。见https://www.typescriptlang.org/docs/handbook/generics.html
new Vue<{ count: number }, { initialize: () => void }, {}, {}>({
//...
data:{
count: 0
},
methods:{
initialize: function() {
this.count = count + 1;
},
}
});
回答by PuncrOc
I ran into similar problems (especially in .vue files). I did find that this seemed to fix the problem however. Anywhere you import .vue files, change the ES6 style "import" to "require" instead.
我遇到了类似的问题(尤其是在 .vue 文件中)。我确实发现这似乎解决了问题。在任何地方导入 .vue 文件,请将 ES6 样式“导入”更改为“需要”。
So in your example, change:
所以在你的例子中,改变:
import Competency from '../components/competency.vue';
to...
到...
declare var require: any;
var Competency = require("../components/competency.vue").default;
回答by Buksy
I suggest using class based components when using typescript (have a look at this "Writing Class-Based Components with Vue.js and TypeScript"). This is the only way to have type safe code and use autocomplete functionality of your IDE
我建议在使用 typescript 时使用基于类的组件(看看这个“Writing Class-Based Components with Vue.js and TypeScript”)。这是拥有类型安全代码并使用 IDE 的自动完成功能的唯一方法
You need to install vue-property-decorator
Here is an example of class based component:
下面是一个基于类的组件的例子:
import { Component, Vue, Watch } from 'vue-property-decorator'
@Component({
props: {
prop1: { type: Number }
}
})
export default class MyComponent extends Vue {
// This is how you define computed
get myComputedRoute() {
return this.$route.params;
}
@Watch('myComputedRoute')
onPropertyChanged(value: string, oldValue: string) {
// Do stuff with the watcher here.
}
}