Property or method 'componentNames' is not defined even though it is defined
P粉514001887
P粉514001887 2024-02-17 21:22:44
0
1
362

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粉514001887
P粉514001887

reply all(1)
P粉085689707

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
  },
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!