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 :)
Top comments (7)
Thank you for sharing! I didn't know about that library, but in such cases I'd use the
$parent
property.Example:
suppose you extended more than one mixin. And all the mixin have same method name. Is
$parent
will work?No you can't, but if you control the mixins, isn't it easier to change the name of the methods?
yeah, that's good I know. Thanks
Cool, Thanks for sharing. I was looking for something you did share here.
Btw, it was written by me :p
Yes. I know that :D