打工的小兵
2021-08-05 16:59
采纳率: 100%
浏览 155

Vue2.x使用TypeScript写法extends super报错

Super.vue

<script lang="ts">
import Vue from "vue"
import Component from "vue-class-component"

@Component
export default class  extends Vue {
    baseMethod() {
        console.log("I am BaseMethod!");
    }
}
</script>

Test.vue

<template>
    <div class="test">
        hello world
    </div>
</template>

<script lang="ts">
import Component from "vue-class-component"
import Super from "./Super.vue"

@Component
export default class Test extends Super {
    baseMethod() {
        console.log("I am TestMethod!");
        super.baseMethod();
    }
    mounted() {
        this.baseMethod();
    }
}
</script>

只要一运行就会报错:
Test.vue:Cannot read property 'call' of undefined
不能用的话,我怎么调用Super父类的方法呢?

  • 收藏

3条回答 默认 最新

  • 时间就是成长 2021-08-06 10:44
    已采纳

    原型原型链的底层在ES6语法中是有setPrototypeOf和getPrototypeOf可以通过主关改变原型链去做,下附逻辑

    @Component
    export default class Test extends Super {
        baseMethod() {
            console.log("I am TestMethod!");
            let proto = function T(){}
            const temp = Object.setPrototypeOf(proto.prototype, Super);
            Object.getPrototypeOf(temp).extendOptions.methods.baseMethod.call(this)
        }
        mounted() {
            this.baseMethod();
        }
        static staticMethod() {
            console.log("I am TestStaticMethod!");
            super.staticMethod();
        }
    }
    
    
    1 打赏 评论
  • variation8 2021-08-05 17:54

    import Super from "./Super.vue"改为import baseMethod from "./Super"调用的是上级的方法

    打赏 评论
  • 指尖电光 2021-08-05 21:05

    在子类里可以直接通过this调用父类方法吧

    打赏 评论

相关推荐 更多相似问题