Call super method in Vue Component
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.
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?
There is a library for making this possible. Source Vue Super Call
npm install vue-super-call
import VueSuperMethod from 'vue-super-call'
Vue.prototype.$super = VueSuperMethod
this.$super(Mixin).yourMethod()
// 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 😃