首页  >  问答  >  正文

属性或方法“componentNames”未定义,即使已定义

我收到了如标题所示的错误。我读了一些有关此错误的信息,大多数答案都说它与引用不存在的方法/数据属性有关,或者是由愚蠢的拼写引起的。在下面的代码块中,我正确引用了现有的 componentNames 数据属性。我注意到,只有当我在 componentNames 上使用 Object.keys() 方法(用于获取组件名称)时,才会出现此问题。

<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>

错误:

[Vue warn]: 属性或方法“componentNames”未定义 实例但在渲染期间引用。

P粉514001887P粉514001887244 天前377

全部回复(1)我来回复

  • P粉085689707

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

    尝试使用空数组初始化 componentNames,然后在创建的钩子内将 Object.keys($options.components) 分配给它:

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

    回复
    0
  • 取消回复