uni-app vue3 小程序 template v-for 设置 key 报错

uni-app vue3 小程序 template v-for 设置 key 报错

示例代码:

<template v-for="(item, index) in arr" :key="index">  
    <view>{{item}}</view>  
</template>

操作步骤:

  • vue 版本选择 3
  • 运行到小程序

预期结果:

  • 正常编译

实际结果:

  • 报错 <template> cannot be keyed

bug描述:

vue3 要求 <template v-for>key 设置在 template 标签上(详细

但是在 template 上加 key 编译到小程序报错 <template> cannot be keyed,编译到 App 正常

如果把 key 加在子节点上,则编译到小程序正常,编译到 App 报错 <template v-for> key should be placed on the <template> tag


更多关于uni-app vue3 小程序 template v-for 设置 key 报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html

7 回复

预计下个alpha版本支持,已加分,感谢您的反馈!

更多关于uni-app vue3 小程序 template v-for 设置 key 报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html


更新至最新HBuilderX Alpha

最新版,3.3.8.20220114-alpha还是这样

<template>
</template> 别死板绑定在template上,里面包个div
<template>
</template>

回复 1***@qq.com: 这样会多一个不必要的层

在 uni-app 的 Vue 3 环境下,<template v-for>key 设置确实存在平台差异问题。这是由于 Vue 3 本身要求 key 必须放在 <template> 标签上,但部分小程序平台的原生模板语法不支持在 <template> 上设置 key 属性。

解决方案:

目前最稳定的跨平台兼容方案是避免直接使用 <template v-for>,改用普通的块级元素包裹:

<view v-for="(item, index) in arr" :key="index">
  <view>{{item}}</view>
</view>

如果必须使用 <template> 且需要兼容所有平台,可以采用条件编译的方式:

<!-- #ifdef MP-WEIXIN || MP-ALIPAY -->
<view v-for="(item, index) in arr" :key="index">
  <view>{{item}}</view>
</view>
<!-- #endif -->

<!-- #ifndef MP-WEIXIN -->
<template v-for="(item, index) in arr" :key="index">
  <view>{{item}}</view>
</template>
<!-- #endif -->
回到顶部