Home > front end >  Property or method "componentNames" is not defined even though it's defined
Property or method "componentNames" is not defined even though it's defined

Time:12-01

I got the error as shown in the title. I read a bit about this error and most answers say that it's about referring to non-existing method/data properties or it's caused by a silly spelling. In the following chunk of code I refer to existing componentNames data property correctly. I've noticed, that this issue arises only when I use Object.keys() method (as to get to component names) on componentNames.

<template>
  <v-container fluid>
    <v-row dense>
      <v-col
        v-for="(comp, n) in componentNames"
        :key="n"
        :cols="n === 0 ? 2 : 10"
        >    
          <v-card>
            <component :is="comp"></component>
          </v-card>

      </v-col>
    </v-row>
  </v-container>
</template>

<script>
import A from '../views/A.vue';
import B from '../views/B.vue';

export default {
  name: 'Project',

  data() {
    return {
      //componentNames: ['A', 'B']  // when I use this line of code then it works perfectly
      componentNames: Object.keys(this.$options.components) // however, this line doesn't work
    }
  },
  components: {
    A,
    B
  },
};
</script>

Error:

[Vue warn]: Property or method "componentNames" is not defined on the instance but referenced during render.

CodePudding user response:

Try to init componentNames with an empty array then assign Object.keys($options.components) to it inside created hook:

 data() {
    return {
      componentNames: []
    }
  },
created(){
    this.componentNames=Object.keys(this.$options.components)
},
  components: {
    A,
    B
  },
  • Related