带有TypeScript的Nuxt.js:类型“y”上不存在属性“x”
我是 Vue 和 Nuxt 的新手。目前正在使用 TypeScript 做一个教程。它给我抛出了Property 'x' does not exist on type 'y'.下面一个例子的一堆错误;
ERROR in components/AboutMe.vue:56:27
TS2339: Property 'routes' does not exist on type '{ components: { CButton: any; }; props: { user: { type: ObjectConstructor; default: undefined; }; }; data(): { expand: boolean; showTitle: boolean; showReadMore: boolean; routes: string[]; compiledBio: string; }; beforeMount(): void; mounted(): void; }'.
54 | },
55 | mounted() {
> 56 | this.showTitle = this.routes.every((r) => this.$route.name !== r)
| ^^^^^^
57 | if (this.$route.name === `users-userSlug`) {
58 | this.expand = true
59 | this.showReadMore = false
其他人是Property 'showTitle' does not exist,'expand'等等。基本上所有的东西都会this.抛出错误。
这是组件<script块AboutMe.vue。
<script lang="ts">
import { CButton } from '@chakra-ui/vue'
export default {
components: {
CButton,
},
props: {
user: {
type: Object,
default: undefined,
},
},
data() {
return {
expand: false,
showTitle: false,
showReadMore: true,
routes: [`users-userSlug-posts`, `users-userSlug`],
compiledBio: ``,
}
},
mounted() {
this.showTitle = this.routes.every((r) => this.$route.name !== r)
if (this.$route.name === `users-userSlug`) {
this.expand = true
this.showReadMore = false
}
},
}
</script>
请帮助我,我做错了什么?
nuxt.js (v2.14.6)
编辑 1:回复@BoussadjraBrahim
谢谢,我补充说Vue.extend({}),现在大多数错误都消失了。但其中一些仍然存在。
<script lang="ts">
import { CButton } from '@chakra-ui/vue'
export default {
components: {
CButton,
},
props: {
user: {
type: Object,
default: undefined,
},
},
data() {
return {
expand: false,
showTitle: false,
showReadMore: true,
routes: [`users-userSlug-posts`, `users-userSlug`],
compiledBio: ``,
}
},
mounted() {
this.showTitle = this.routes.every((r) => this.$route.name !== r)
if (this.$route.name === `users-userSlug`) {
this.expand = true
this.showReadMore = false
}
},
}
</script>
export default Vue.extend({
data() {
const showAboutUs: Boolean = false
const isOpen: Boolean = false
return {
showAboutUs,
isOpen,
}
},
mounted() {
this.showAboutUs = this.$route.name !== `users-userSlug-posts`
},
methods: {
open() {
this.isOpen = true
},
close() {
this.isOpen = false
},
},
})
回答
要获得类型推断,您应该使用Vue.extend({})以下方法创建组件:
<script lang="ts">
import { CButton } from '@chakra-ui/vue'
import Vue from "vue"
export default Vue.extend({
components: {
CButton,
},
props: {
user: {
type: Object,
default: undefined,
},
},
data() {
return {
expand: false,
showTitle: false,
showReadMore: true,
routes: [`users-userSlug-posts`, `users-userSlug`],
compiledBio: ``,
}
},
mounted() {
this.showTitle = this.routes.every((r) => this.$route.name !== r)
if (this.$route.name === `users-userSlug`) {
this.expand = true
this.showReadMore = false
}
},
})
</script>
我建议输入您的数据属性以强制执行组件输入:
data() {
const routes:Array<string>: [`users-userSlug-posts`, `users-userSlug`];
// do the same thing with the other properties
return {
expand: false,
showTitle: false,
showReadMore: true,
routes,
compiledBio: ``,
}
},