You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3+TypeScript报错:Property 'totalVuePackages'不存在于对应类型

Vue3 + TypeScript 类型报错修复方案

问题核心原因

Vue3选项式API在TypeScript环境下,若未使用defineComponent包裹组件选项,TypeScript无法正确推断组件实例的类型,导致无法识别data中定义的属性,从而抛出类型错误。

修复步骤及代码

  1. 引入Vue的defineComponent方法
  2. 用defineComponent包裹整个组件选项对象
  3. 补上未在data中声明的errorMessage属性
  4. 修正接口数据的使用(jsonplaceholder的/posts返回数组,无total字段)

修改后的完整代码:

<script lang='ts'>
import axios from 'axios';
import { defineComponent } from 'vue';

export default defineComponent({
  name: 'componentHome',

  data(){
    return{
      totalVuePackages: '',
      errorMessage: ''
    }
  },

  created() {
    axios.get("https://jsonplaceholder.typicode.com/posts")
      .then(response => {
        // 示例:取返回数组的长度作为统计值
        this.totalVuePackages = response.data.length.toString();
      })
      .catch(error => {
        this.errorMessage = error.message;
        console.error("There was an error!", error);
      });
  }
});
</script>

额外说明

  • defineComponent是Vue3为TypeScript提供的类型推断工具,能自动识别组件的data、methods、生命周期钩子等类型,彻底解决选项式API中的类型报错问题。
  • 若你需要获取total类的统计值,需确认是否调用了正确的接口,jsonplaceholder的/posts仅返回帖子列表数据,无总数字段。

内容的提问来源于stack exchange,提问作者макс ol

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 00:31:17