如果有人对 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 的开发人员(我认为这允许将 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);
// expected output: "cheese"