MyF*_*512 17 javascript vue.js
是否可以在Vue.js中使用方法覆盖?
var SomeClassA = Vue.extend({
methods: {
someFunction: function () {
// ClassA some stuff
}
}
});
var SomeClassB = SomeClassA.extend({
methods: {
someFunction: function () {
// CALL SomeClassA.someFunction
}
}
});
Run Code Online (Sandbox Code Playgroud)
我想从ClassB someFunction调用ClassA someFunction.它甚至可能吗?
nil*_*ils 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();
}
}
});
Run Code Online (Sandbox Code Playgroud)
并在SomeComponentA的模板中:
<some-component-b someFunctionParent="someFunction"></some-component-b>
Run Code Online (Sandbox Code Playgroud)
混合物
如果这是您想在其他地方使用的常用功能,那么使用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();
}
}
});
Run Code Online (Sandbox Code Playgroud)
3.呼唤父道具(亲子,丑陋)
// In someComponentB's 'someFunction':
this.$parent.$options.methods.someFunction(...);
Run Code Online (Sandbox Code Playgroud)
如果有人对 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');
},
}
}
Run Code Online (Sandbox Code Playgroud)
jsfiddle:https ://jsfiddle.net/7b3tx0aw/2/
更多信息:
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"
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10981 次 |
| 最近记录: |