【问题标题】:Use v-for create components inside div in vue js在 vue js 中使用 v-for 在 div 内创建组件
【发布时间】:2022-01-03 15:28:40
【问题描述】:

我想遍历一个 json 对象并为每个元素创建一个组件,该组件的道具也来自该对象

在div里面插入一个

<div class="row" v-for="item in projectsJson">

我使用 div 来获取引导类。

这确实创建了两个 div 而不是一个。期望的结果是一个装满组件的 div 容器。

我使用了与 react 相同的逻辑,这在 vue 中的工作方式不同吗?

jsonObj = 
[
  {
    "name": "proj1",
    "descr": "stuff",
    "stack": ["which", "other lib"],
    "imgPath": "."
  },
  {
    "name": "proj2",
    "descr": "stuffsss",
    "stack": ["which ", "other "],
    "imgPath": "."
  }
]

<template>
 <div class="row" v-for="item in projectsJson">
        <project-comp
        :project_name="item.name" />
      </div>
</template>

【问题讨论】:

    标签: javascript vue.js for-loop vue-component


    【解决方案1】:

    如果您需要一个具有 row 类的 div 以及其中的所有子组件,您应该将 v-for 移动到组件而不是 div。

    React 也有同样的行为。循环应用到哪个组件,它将在 DOM 中重复。

    <div class="row" >
        <project-comp
            v-for="item in projectsJson"
            :project_name="item.name" />
    </div>
    

    【讨论】:

      【解决方案2】:

      在 Vue.js 中,v-for 应用于属性所在的 DOM 元素。另外,不要忘记key 你应该这样做:

      <template>
        <div class="row">
          <project-comp 
            v-for="item in projectsJson" 
            :project_name="item.name" 
            :key="project.name" <!-- The key should be unique in the array, use name if it is unique, or use id -->
          />
        </div>
      </template>
      

      【讨论】:

      • 这个答案和我的一样。答案的解决方案是将 v-for 移动到组件级别。不是v-for 的密钥。用户应该在他的第一个实现本身中考虑到密钥的使用。
      • @Nitheesh 为 OP 提供额外信息有什么问题?
      • 附加信息永无止境。因此,任何人都可以在您的实施之上添加另一个答案。
      • @Nitheesh 我在答案中添加了密钥,因为在我的答案中提供 vue.js 代码感觉不对,这会导致 Vue.js 警告
      猜你喜欢
      • 2022-01-05
      • 1970-01-01
      • 1970-01-01
      • 2019-11-10
      • 2017-12-01
      • 2020-03-29
      • 2017-04-04
      • 2020-07-01
      • 1970-01-01
      相关资源
      最近更新 更多