Is it possible to use method overriding in Vue.js?
var SomeClassA = Vue.extend({ methods: { someFunction: function() { // ClassA some stuff } } }); var SomeClassB = SomeClassA.extend({ methods: { someFunction: function() { // CALL SomeClassA.someFunction } } });
I want to call ClassA someFunction from ClassB someFunction. Is it even possible?
To call parent method with component with Vue. js, we can get the parent component's method from the $parent property. to define the child component with Vue. component .
To call function on child component on parent events with Vue. js, we can assign the ref to the child component and then call the method in the parent when the event is emitted. to add a template with the child-component added. We assign a ref to it.
To call a method in a child component with Vue. js, we can pass in a prop from the parent component to its child. Then in the child component, we watch the prop's value and run the method we want. in the child component to register the testProp prop and add the sayHello method.
No, vue doesn't work with a direct inheritance model. You can't A.extend
an component, as far as I know. It's parent-child relationships work mainly through props and events.
There are however three solutions:
1. Passing props (parent-child)
var SomeComponentA = Vue.extend({ methods: { someFunction: function () { // ClassA some stuff } } }); var SomeComponentB = Vue.extend({ props: [ 'someFunctionParent' ], methods: { someFunction: function () { // Do your stuff this.someFunctionParent(); } } });
and in the template of SomeComponentA:
<some-component-b someFunctionParent="someFunction"></some-component-b>
2. Mixins
If this is common functionality that you want to use in other places, using a mixin might be more idiomatic:
var mixin = { methods: { someFunction: function() { // ... } } }; var SomeComponentA = Vue.extend({ mixins: [ mixin ], methods: { } }); var SomeComponentB = Vue.extend({ methods: { someFunctionExtended: function () { // Do your stuff this.someFunction(); } } });
3. Calling parent props (parent-child, ugly)
// In someComponentB's 'someFunction': this.$parent.$options.methods.someFunction(...);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With