代码之家  ›  专栏  ›  技术社区  ›  daredellMountain

使用循环编译vue文件时出现Eslint错误

  •  0
  • daredellMountain  · 技术社区  · 2 年前

    我正在尝试用Vue3制作一个动态页面。我创建了一个Projects.json文件,其中包含一个包含数据的数组。我想在MainContainerContent.vue文件中显示这些数据。我在App.vue和MainContainer.vue中制作了一个v-for,以循环json文件中的项目。

    我现在有一个问题,我在v-for上得到了这个错误: Custom elements in iteration require 'v-bind:key' directives 它说这与eslint插件vue有关。我已经运行了命令: npm remove @vue/cli-plugin-eslint 但我在编译时仍然会遇到这个错误。

    有人能向我解释一下我怎样才能摆脱这个错误吗?由于出现了这个错误,我无法运行我的应用程序,因此我无法测试我编写的代码是否有效。

    应用.vue

    <template>
      <MainContainer/>
    
      <section
        class="flex flex-col items-center pb-8"
        v-for="project in projects">
          <h2
          role="title"
          class="text-3xl font-bold"
          >{{ project.name }}</h2>
          <MainContainer
          :project="project"
          />
        </section>
    </template>
    
    <script setup>
      import { projects } from './Projects.json'
      import MainContainer from './components/mainContainer.vue';
      import './assets/tailwind.css';
    </script>
    

    主容器.vue

    <template>
      <Header/>
      <Content
        v-for="project in projects.project"
        :project="project"
      />
    </template>
    
    <script setup>
      import Header from './mainContainerHeader.vue';
      import Content from './mainContainerContent.vue';
    </script>
    
    <script>
    export default {
      props: {
        projects: {
          default: null,
          type: Object,
        }
      }
    }
    </script>
    

    主容器内容.vue

    <template>
      <div>
          <p
          class="p-3 border-r-2 border-r-gray-500"
          >{{ project.name }}</p>
          <p
          class="p-3 border-r-2 border-r-gray-500"
          >{{ project.description }}</p>
          <p
          class="p-3"
          >{{ project.link }}</p>
      </div>
    </template>
    
    <script>
    export default {
      props: {
        project: {
          default: null,
          type: Object,
        }
      }
    }
    </script>
    

    项目.json

    {
      "projects": [
        {
          "name": "Projects",
          "project": [
            {
              "name": "Project #1",
              "description": "Project #1",
              "link": "www.google.be"
            },
            {
              "name": "Project #2",
              "description": "Project #2",
              "link": "www.google.be"
              }
          ]
        }
      ]
    }
    
    1 回复  |  直到 2 年前
        1
  •  1
  •   Bergur    2 年前

    我建议解决并修复错误:)

    错误是告诉您缺少密钥绑定,这有助于Vue跟踪每个项目。更多信息,请访问: https://vuejs.org/guide/essentials/list.html#maintaining-state-with-key

    因此,只需添加key指令并将值设置为唯一值即可。

    <section
        class="flex flex-col items-center pb-8"
        v-for="project in projects"
        :key="project.name"
    >
    

    假设名称是唯一的,您还可以向json文件添加一个id属性,并将其用作密钥。