vue.jsvuejs2vue-componentparent-childvue-class-components

Property 'method' does not exist on type 'Vue'.Vetur(2339) when trying to access parent method from child component (with class-based vue components)


I am using class-based vue components and am trying to access a parent's (of a parent's) method within a child component for various reasons. The syntax is as follows for the definition of my class-component and the line where I try to access the parent method:

export default class ListStoragePlace extends Vue {

    @Prop({ required: true })
    readonly id!: number
    checkbox: boolean = false

    @Watch("checkbox")
    onPropertyChanged() {
        this.$parent.$parent.updateSelected(this.id, this.checkbox)
    }
}

The code functions as intended and it calls up the parent method on a property change in the child, but the Vetur plugin (for Vue 2 projects) still sees it as an error, thus breaking pipelines and causing other issues.

This is the specific error: error example

The parent component and its method is defined as follows:

export default class Table extends Vue {
    updateSelected(id: number, status: boolean) {
        if (status) {
            this.selected.push(id)
        } else {
            for (let i = 0; i < this.selected.length; i++) {
                if (this.selected[i] === id) {
                    this.selected.splice(i, 1)
                }
            }
        }
    }
}

If anyone has a solution or even simply a workaround to get rid of the error, please let me know.


Solution

  • First and foremost, it is important to realize this.$parent is a terrible practice and should not be used (it is a remnant functionality from Vue 1).

    If you desperately need a temporary work-around, you can use the following syntax to remove the error (solution given by @Estus Flask):

    (this.$parent.$parent as unknown as MyCompType).updateSelected(...)
    

    MyCompType is the name of your class-based component.

    Docs: https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#type-assertions