是否可以在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。它甚至可能吗?
答案 0 :(得分:15)
不,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。调用父道具(父子,丑陋)
// In someComponentB's 'someFunction':
this.$parent.$options.methods.someFunction(...);
答案 1 :(得分:1)
万一有人要求解决,这里是我的并且工作正常:
var SomeClassA = {
methods: {
someFunction: function () {
this.defaultSomeFunction();
},
// defaultSomeFunction acts like parent.someFunction() so call it in inheritance
defaultSomeFunction: function () {
// ClassA some stuff
},
},
};
var SomeClassB = {
extends: SomeClassA,
methods: {
someFunction: function () {
// Replace the wanted SomeClassA::someFunction()
this.defaultSomeFunction();
// Add custom code here
},
},
};
使用https://vuejs.org/v2/api/#extends中的Juste extends
代替Vue.extends()
的用法
答案 2 :(得分: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/
更多信息:
this
指针替换匿名函数调用都不应该是魔术)。