所有 vue 道具和数据都给出了错误“属性”不存在于类型“与打字稿

Qwe*_*tie 8 typescript vue.js

我最近在我的 vue 项目中添加了 typescript,每次访问 props 或 data 中的值时,我都会收到此错误

37:46 Property 'activity' does not exist on type '{ props: { activity: { type: ObjectConstructor; required: boolean; }; }; methods: { formatDistance: (distance: number, setting_unit: string) => string; }; mounted: () => void; }'.
    35 |         },
    36 |         mounted: function () {
  > 37 |             var activitymap = L.map('map' + this.activity['activity']['id']).setView([51.505, -0.09], 13)
       |                                              ^
Run Code Online (Sandbox Code Playgroud)

这是我的道具

    props: {
        activity: {
            type: Object,
            required: true
        }
    },
Run Code Online (Sandbox Code Playgroud)

这是它正在使用的方法

    mounted: function () {
        var activitymap = L.map('map' + this.activity['activity']['id']).setView([51.505, -0.09], 13)
        L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', {
            attribution: '<a href="https://www.openstreetmap.org/">OpenStreetMap</a>',
            maxZoom: 18,
            id: 'mapbox.streets',
            accessToken: process.env.VUE_APP_MAPBOX_KEY
        }).addTo(activitymap)

        var gpxGroup = new L.FeatureGroup();

        activitymap.addLayer(gpxGroup);

        omnivore.gpx(this.activity['activity']['activity_log_url']).addTo(gpxGroup).on('ready',
            function () {
                activitymap.fitBounds(gpxGroup.getBounds());
            }
        )
    }
Run Code Online (Sandbox Code Playgroud)

什么可能导致这个问题?

HTN*_*HTN 11

在没有 vue-class-component 的情况下,很难在 VueJS 中使用 typescript。你Vue.extend()用来定义你的组件吗?

import Vue from 'vue';
export default Vue.extend({
    props: {
        activity: {
            type: Object,
            required: true
        }
    },
});
Run Code Online (Sandbox Code Playgroud)


Jos*_*sen 8

在 Vue 3 中,我通过将导出的组件字典包装在defineComponent.

https://v3.vuejs.org/guide/typescript-support.html#defining-vue-components

import Vue from 'vue';

export default Vue.defineComponent({
    data() { ... },
    methods: { ... },
    ...
});
Run Code Online (Sandbox Code Playgroud)

  • 好的,在这里找到:https://v3.vuejs.org/guide/typescript-support.html#defining-vue-components (2认同)