如何在Vue 3中用v-for根据数组生成动态插槽?
Vue3 动态生成作用域插槽实现方案
直接通过v-for结合动态插槽名语法就能实现,无需硬编码多个插槽模板,具体代码如下:
<template> <table> <!-- 遍历字符串数组,动态生成插槽 --> <template v-for="key in ['hello1', 'hello2', 'hello3']" :key="key" v-slot:[`item.${key}`]="{ item }" > {{ item[key] }} </template> </table> </template>
关键说明
- 动态插槽名使用方括号语法:
v-slot:[动态表达式],这里通过模板字符串拼接出item.hello1、item.hello2这类目标插槽名 - 给
v-for循环的每个插槽绑定唯一key,符合Vue的列表渲染规范 - 作用域插槽接收的
item对象,通过方括号语法item[key]动态访问对应属性,避免硬编码属性名
如果插槽名数组是组件内的响应式变量(比如data或props传入),直接替换即可,示例如下:
<script setup> // 定义响应式插槽名数组 const slotKeys = ['hello1', 'hello2', 'hello3'] </script> <template> <table> <template v-for="key in slotKeys" :key="key" v-slot:[`item.${key}`]="{ item }" > {{ item[key] }} </template> </table> </template>
内容的提问来源于stack exchange,提问作者omega
相关产品推荐
相关产品推荐

