Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if Vue component extends another

Tags:

vue.js

vuejs2

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!

like image 940
Myupe Avatar asked Dec 17 '17 11:12

Myupe


1 Answers

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>
like image 98
Decade Moon Avatar answered Nov 06 '22 13:11

Decade Moon