Vue.js inheritance call parent method

前端 未结 3 1297
生来不讨喜
生来不讨喜 2021-02-05 07:28

is it possible to use method overriding in Vue.js?

var SomeClassA = Vue.extend({
    methods: {
        someFunction: function () {
            // ClassA some st         


        
3条回答
  •  盖世英雄少女心
    2021-02-05 07:50

    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:

    
    

    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(...);
    

提交回复
热议问题