Vue.js inheritance call parent method

前端 未结 3 1302
生来不讨喜
生来不讨喜 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 08:02

    In case someone's interested in a JustWorksTM solution:

    var FooComponent = {
      template: '',
    
      data: function () {
       return {
         foo: 1,
         bar: 'lorem',
         buttonLabel: 'Click me',
       }
      },
    
      methods: {
        fooMethod: function () {
          alert('called from FooComponent');
        },
        
        barMethod: function () {
          alert('called from FooComponent');
        },
      }
    }
    
    var FooComponentSpecialised = {
      extends: FooComponent,
    
      data: function () {
       return {
         buttonLabel: 'Specialised click me',
         zar: 'ipsum',
       }
      },
    
      methods: {
        fooMethod: function () {
          FooComponent.methods.fooMethod.call(this);
        
          alert('called from FooComponentSpecialised');
        },
      }
    }
    

    jsfiddle: https://jsfiddle.net/7b3tx0aw/2/


    More info:

    1. This solution is for devs that can't use TypeScript for some reason (which I think allows defining vue components as classes, which in turn allows full inheritance feature-set).
    2. Further elaboration about the solution (whys and hows): https://github.com/vuejs/vue/issues/2977
    3. This ain't that ugly, considering that no rocket science is used here (calling anonymous functions with the this pointer replaced should be no magic for any decent js dev).

    How to use Function.prototype.call()

    Reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call

    Sample code:

    function Product(name, price) {
      this.name = name;
      this.price = price;
    }
    
    function Food(name, price) {
      Product.call(this, name, price);
      this.category = 'food';
    }
    
    console.log(new Food('cheese', 5).name);
    // expected output: "cheese"
    

提交回复
热议问题