首页 > 解决方案 > 类型 '{ $route(currentRoute: any): void; 上不存在属性 }' 在 Ionic Vue 中

问题描述

所以我目前正在使用 Vue 和 TypeScript 开发 Ionic WebApp。现在,我尝试获取由路由解析的当前 id。为此,我正在研究一个观察者:

export default {
  data() {
    return {
      productId: null,
    };
  },
  watch: {
    $route(currentRoute: any) {
      this.productId = currentRoute.params.id;
    },
  },
};

这是我收到的错误消息:

[vue-cli-service] TS2339: Property 'productId' does not exist on type '{ $route(currentRoute: any): void; }'.
[vue-cli-service]     14 |   watch: {
[vue-cli-service]     15 |     $route(currentRoute: any) {
[vue-cli-service]   > 16 |       this.productId = currentRoute.params.id;
[vue-cli-service]        |            ^^^^^^^^^
[vue-cli-service]     17 |     },
[vue-cli-service]     18 |   },
[vue-cli-service]     19 | };

我已经尝试过使用处理程序表示法,但这也不起作用。其他人有想法吗?

标签: typescriptvue.jsionic-framework

解决方案


在 components 中启用类型推断Vue.extend(),请在导出的组件定义上使用:

import Vue from 'vue'
                    
export default Vue.extend({
  data() {
    return {
      productId: null,
    }
  },
  watch: {
    $route(currentRoute: any) {
      this.productId = currentRoute.params.id
    }
  }
})

推荐阅读