如果有人对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/
更多信息:
- 此解决方案适用于无法使用TypeScript的开发人员(我认为TypeScript允许将vue组件定义为类,从而允许完整的继承功能集)。
- 有关该解决方案的进一步阐述(原因和方法):https://github.com/vuejs/vue/issues/2977
- 考虑到这里没有使用任何高深技术(调用带替换的
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);
SomeAbstractComponentA
。我从Ember转到Vue,我认为组件中的继承并没有什么问题。 - MyFantasy512A.extend
。如果你想从一个独立的组件(不在父子关系中)进行扩展,目前唯一的选择是 mixins。实际方法覆盖仅在 JavaScript 的 ES6 类中引入,它不是该语言的本地功能。 - nils