slot-scope 语法过时了

slot-scope 语法在 Vue 3 中已经被废弃(deprecated),并且在 Vue 2.6+ 版本中就已经被更统一、更清晰的 v-slot 指令 所取代。


✅ 正确用法(Vue 2.6+ 和 Vue 3)

旧语法(已过时):

<my-component>
  <template slot-scope="props">
    {{ props.item.name }}
  </template>
</my-component>

新语法(推荐):

<my-component>
  <template v-slot="props">
    {{ props.item.name }}
  </template>
</my-component>

或者使用简写形式(仅适用于默认插槽):

<my-component v-slot="props">
  {{ props.item.name }}
</my-component>

对于具名插槽(named slots),必须使用 <template> 标签:

<my-component>
  <template #header="props">
    {{ props.title }}
  </template>
  <template #default="item">
    {{ item.text }}
  </template>
  <template #footer>
    静态 footer(无作用域)
  </template>
</my-component>

#headerv-slot:header 的简写。


📌 注意事项

  1. Vue 3 完全移除了 slotslot-scope 属性,只支持 v-slot
  2. 在 Vue 2.6+ 中虽然仍兼容 slot-scope,但官方强烈建议迁移到 v-slot
  3. v-slot 只能用在 <template> 上(或组件标签上用于默认插槽),不能直接用在普通元素上。

🔧 迁移示例

Before(Vue 2.5 及更早)

<list>
  <li slot="item" slot-scope="props">{{ props.text }}</li>
</list>

After(Vue 2.6+ / Vue 3)

<list>
  <template #item="props">
    <li>{{ props.text }}</li>
  </template>
</list>

总结

  • ❌ 不要再使用 slot-scope
  • ✅ 统一使用 v-slot 或其简写 #
  • 这样代码更清晰、一致,并且兼容 Vue 3。
posted @ 2026-01-12 16:53  龙陌  阅读(0)  评论(0)    收藏  举报