Vue.js继承调用父方法

新手上路,请多包涵

是否可以在 Vue.js 中使用方法覆盖?

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

var SomeClassB = SomeClassA.extend({
  methods: {
    someFunction: function() {
      // CALL SomeClassA.someFunction
    }
  }
});

我想从 ClassB someFunction 调用 ClassA someFunction。有可能吗?

原文由 MyFantasy512 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 604
2 个回答

不,vue 不适用于直接继承模型。据我所知,你不能 A.extend 一个组件。它的亲子关系主要通过道具和事件起作用。

不过有以下三种解决方案:

1.传递道具(亲子)

 var SomeComponentA = Vue.extend({
    methods: {
        someFunction: function () {
            // ClassA some stuff
        }
    }
});

var SomeComponentB = Vue.extend({
   props: [ 'someFunctionParent' ],
   methods: {
       someFunction: function () {
           // Do your stuff
           this.someFunctionParent();
       }
   }
});

在 SomeComponentA 的模板中:

 <some-component-b someFunctionParent="someFunction"></some-component-b>

2.混合

如果这是你想在其他地方使用的常用功能,使用 mixin 可能更惯用:

 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.调用parent props(亲子,丑)

 // In someComponentB's 'someFunction':
this.$parent.$options.methods.someFunction(...);

原文由 nils 发布,翻译遵循 CC BY-SA 3.0 许可协议

如果有人对 JustWorksTM 解决方案感兴趣:

 var FooComponent = {
  template: '<button @click="fooMethod()" v-text="buttonLabel"></button>',

  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/


更多信息:

  1. 该解决方案适用于出于某种原因无法使用 TypeScript 的开发人员(我认为这允许将 vue 组件定义为类,这反过来又允许完全继承功能集)。
  2. 关于解决方案的进一步阐述(原因和方式): https ://github.com/vuejs/vue/issues/2977
  3. 这不是那么丑陋,考虑到这里没有使用火箭科学(使用 this 指针替换对于任何体面的 js 开发人员来说应该不是什么魔法)。

如何使用 Function.prototype.call()

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

示例代码:

 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"

原文由 d-ph 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题