NuxtJS(TypeScript)中Vue类型无loading属性的报错解决求助
解决方案
方法一:使用类属性声明数据(推荐)
vue-property-decorator推荐通过类属性的方式声明组件数据,TypeScript可以自动推断属性类型,彻底避免类型报错:
<script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; @Component export default class LoadingBar extends Vue { // 直接在类中声明loading属性,TS自动推断其类型为boolean private loading = false; start(): void { this.loading = true; } finish(): void { this.loading = false; } } </script>
方法二:扩展Vue接口声明属性类型
如果需要保留@Component中的data选项写法,可以通过扩展Vue的类型接口,让TypeScript识别loading属性:
<script lang="ts"> import { Component, Vue } from 'vue-property-decorator'; // 扩展Vue接口,添加loading属性的类型定义 declare module 'vue/types/vue' { interface Vue { loading: boolean; } } @Component({ data: function () { return { loading: false }; }, methods: { start(): void { this.loading = true; }, finish(): void { this.loading = false; }, } }) export default class LoadingBar extends Vue {} </script>
说明
方法一更符合vue-property-decorator的设计规范,代码结构简洁,同时能让TypeScript自动完成类型推断,是优先推荐的解决方案。
内容的提问来源于stack exchange,提问作者grakify
相关产品推荐
相关产品推荐

