Vue.js 继承调用父方法 [英] Vue.js inheritance call parent method
问题描述
是否可以在 Vue.js 中使用方法覆盖?
is it possible to use method overriding in 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.甚至有可能吗?
I want to call ClassA someFunction from ClassB someFunction. Is it even possible?
推荐答案
不,vue 不适用于直接继承模型.据我所知,你不能 A.extend
一个组件.它的亲子关系主要通过道具和事件来运作.
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.传递道具(父子)
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 的模板中:
and in the template of SomeComponentA:
<some-component-b someFunctionParent="someFunction"></some-component-b>
2.混合
如果这是您想在其他地方使用的常见功能,使用 mixin 可能更惯用:
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.调用父道具(亲子,丑)
// In someComponentB's 'someFunction':
this.$parent.$options.methods.someFunction(...);
这篇关于Vue.js 继承调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!