Call super method in Vue Component

Pep Talk

So far (VueJS v2) we don’t have class based component like react. *.vue has it’s own syntax rather than traditional javascript. In that case have you ever feel about calling a method from mixin or another component? Okay!! Let me explain more.

What’s already have?

In ES6 or more we have ability to write class even we have super method to call parent class method. Example is following…

// Defining Parent class in Javascript (ES6)
class Parent {
  getAge() {
    return 52
  }
}

// Defining Child class in Javascript (ES6)
class Child extends Parent {
  getAge() {
    const parentAge = super.getAge()
    // We will get parent ager here. And do further process
  }
}

Have you felt that Vue Component is not allowing this?

Solution for Vue Component

There is a library for making this possible. Source Vue Super Call

How to use in your project?

  • Install it by npm install vue-super-call
  • Add your main.js/index.js (entry file of your project) like following,
import VueSuperMethod from 'vue-super-call'

Vue.prototype.$super = VueSuperMethod

How to call super from method?

  • The basic syntax is this.$super(Mixin).yourMethod()
  • Proper example is following…
// This is mixin
export default {
    name: 'MyMixin',
    methods: {
        sayHello() {
            return "Hello"
        }
    }
}


// Your Component
export default {
    name: 'MyComponent',
    mixins: [MyMixin],
    methods: {
        sayHello() {
            let parentMethodData = this.$super(MyMixin).sayHello()
            console.log(parentMethodData)
            console.log('I am from component after super call')
        }
    }
}

// Console Output
$ Hello
$ I am from component after super call

Have Fun with VueJS 😃