首页 > 解决方案 > 数据更改时,Vue动态组件不会在v-for循环内重新渲染

问题描述

我有动态表组件,我可以在其中修改列(排序、添加新列、删除列)。表体如下所示:

<tr v-for="row in data" :key="row.id">
        <td v-for="column in columns" :key="column.slug">
          <component
            v-if="column.component"
            :is="column.component"
            v-bind="{ row: row, countries: row.reach }"
          />
          <template v-else>
            {{ row[column.slug] }}
          </template>
        </td>
      </tr>

一切正常,除了当我编辑data(添加新列或重新排列顺序)时,表格主体内的每个组件都会消失并且不会呈现。我试图附加唯一:key<component>无法使其工作。当我在 Vue devtools 中检查表体时,我可以看到组件在里面,只是没有渲染到 DOM 中。在 chrome devtools 中检查表体时,我只能看到<!--function(e,n,r,o){return dn(t,e,n,r,o,!0)}-->应该呈现组件的位置。有什么想法我可能在这里做错了吗?

标签: javascriptvue.js

解决方案


您正在使用重复的密钥。v-for您应该为整个组件内的所有元素提供唯一键。试试这个(查看key每一列):

      <tr v-for="row in data" :key="row.id">
        <td v-for="column in columns" :key="`${row.id}/${column.slug}`">
          <component
            v-if="column.component"
            :is="column.component"
            v-bind="{ row: row, countries: row.reach }"
          />
          <template v-else>
            {{ row[column.slug] }}
          </template>
        </td>
      </tr>

此外,当您在开发时,强烈建议使用 Vue 开发模式。它将突出显示这样的错误。


推荐阅读