Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js inheritance call parent method

Tags:

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?

like image 640
MyFantasy512 Avatar asked Apr 21 '16 08:04

MyFantasy512


People also ask

How do you call parent method from child component in Vue?

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 .

How do you call a function on the parent component of a child event?

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.

How do you call a function in child component Vue?

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.


1 Answers

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(...); 
like image 136
nils Avatar answered Sep 25 '22 03:09

nils