I have 2 Vue components which one extends another:
var CompA = { ... }
var CompB = {
extends: CompA,
...
}
I would like check programatically that CompB extends CompA, e.g.:
import CompA from './compA';
import CompB from './compB';
if (CompB instanceof CompA) {
...
}
This code raise the following error:
[Vue warn]: Error in render: "TypeError: Right-hand side of 'instanceof' is not callable"
What is the correct way to do that?
Thanks!
The Vue components CompA
and CompB
are just plain JavaScript objects, there's no kind of subclassing or prototype chains here so instanceof
won't work (not to mention CompA
isn't a Vue instance so it wouldn't work anyway).
You'll have to write your own function to determine if one component extends another:
function extendsComponent(Comp, Super) {
while (Comp) {
if (Comp === Super) {
return true;
}
Comp = Comp.extends;
}
return false;
}
const A = {};
const B = { extends: A };
const C = { extends: B };
if (extendsComponent(C, A)) {
console.log('C extends A (directly or indirectly)');
} else {
console.log('C does not extend A');
}
If you are using Vue.extend
to create your components, then you can use the prototype chain to check for inheritance as you normally would in JavaScript:
const A = Vue.extend({});
const B = A.extend({});
const C = B.extend({});
const Z = Vue.extend({});
console.log(C.prototype instanceof A); // true
console.log(C.prototype instanceof Z); // false
<script src="https://rawgit.com/vuejs/vue/dev/dist/vue.js"></script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With