vue中slot-scope使用v-for时的warning问题

场景

  • 在<a-table>中有插槽位置可以自定义列表的列属性
  • 场景中,有多个相似的自定义列,就想用v-for,但是按通常的写法,直接对<span>使用for会报warning,虽然能正常运行,但是强迫症表示不能接收有warning
    <a-table
      :data-source="list"
      :columns="columns"
      :rowKey="(record, index) => record.id"
    >
      <span :slot="item.name" slot-scope="text, record" v-for="(item, index) in extraTableHeads" :key="index">
        <a @click="callFather(record.id, item.funcName)" style="color: #1890FF;">{{ item.value }}</a>
      </span>
    </a-table>
    
  • Warning: (Emitted value instead of an instance of Error) Ambiguous combined usage of slot-scope and v-for on (v-for takes higher priority). Use a wrapper <template> for the scoped slot to make it clearer

解决

  • 其实这次的问题基本是照搬这个老哥的,一开始觉得这个问题还挺特殊的,应该很难找到相似的案例提供思路,没想到真有一模一样的情况的,而且这个老哥甚至还猜出了我自己的尝试过程,牛逼。但还是记录下吧,特别鸣谢Cookysurongbin
  • 首先导致这个错误的原因是v-for和slot-scope在同一级,意思就是可能会导致渲染的唯一性不确定。提示说,在外面包一层template,行,那我们就把v-for给template
    <a-table
      :data-source="list"
      :columns="columns"
      :rowKey="(record, index) => record.id"
    >
      <template v-for="(item, index) in extraTableHeads" :key="index">
        <span :slot="item.name" slot-scope="text, record">
          <a @click="callFather(record.id, item.funcName)" style="color: #1890FF;">{{ item.value }}</a>
        </span>
      </template>
    </a-table>
    
  • 结果直接从warning升级成了error:<template> cannot be keyed. Place the key on real elements instead. 也就是说,template不能用key来标记,所以再改一改:
    <a-table
      :data-source="list"
      :columns="columns"
      :rowKey="(record, index) => record.id"
    >
      <template v-for="(item, index) in extraTableHeads" :slot="item.name" slot-scope="text, record">
        <span :key="index">
          <a @click="callFather(record.id, item.funcName)" style="color: #1890FF;">{{ item.value }}</a>
        </span>
      </template>
    </a-table>
    
  • 没想到吧,把key放到里面,把slot放外面,看起来很奇怪,但是成了
posted @ 2022-07-18 15:14  Mizuki-Vone  阅读(1419)  评论(0)    收藏  举报