search

Home  >  Q&A  >  body text

Property or method 'componentNames' is not defined even though it is defined

I received the error as shown in the title. I've read a bit about this error and most of the answers say it has to do with referencing a non-existent method/data property, or is caused by stupid spelling. In the code block below, I'm correctly referencing the existing componentNames data property. I noticed that this problem only occurs when I use the Object.keys() method (which is used to get the 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>

mistake:

[Vue warn]: Property or method 'componentNames' is undefined instance but referenced during rendering.

P粉514001887P粉514001887328 days ago427

reply all(1)I'll reply

  • P粉085689707

    P粉0856897072024-02-18 19:27:15

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

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

    reply
    0
  • Cancelreply