[译] Vue 3 迁移策略 —— Slots 统一性(破坏性改动)

2,042 阅读1分钟

需要调研 vue 2 到 vue 3 的迁移方案,来做内部分享。

我看网上貌似目前只有一人翻译了,翻译了前几章。

但是我着急用,只能自己翻了。译者四级没过,全靠有道和谷歌了。

vue 3 官方文档原文—— slots unification

统一 Slots

概览

此次更改统一了 3.x 中的常规插槽和作用域插槽。

以下是更改内容的简要摘要:

  • this.$slots 现在将插槽作为函数暴露出来
  • BREAKING: this.$scopedSlots 已移除

2.x 语法

当使用渲染函数,即 h 时,2.x 用于在内容节点上定义 slot 数据属性。

// 2.x 语法
h(LayoutComponent, [
  h('div', { slot: 'header' }, this.header),
  h('div', { slot: 'content' }, this.content)
])

另外,在引用作用域插槽时,可以使用以下语法来引用它们:

// 2.x 语法
this.$scopedSlots.header

3.x 语法

3.x 中,插槽被定义为当前节点的子对象:

// 3.x 语法
h(LayoutComponent, {}, {
  header: () => h('div', this.header),
  content: () => h('div', this.content)
})

而且,当您需要以编程方式引用作用域内的插槽时,它们现在已合并到 $slots 选项中。

// 2.x 语法
this.$scopedSlots.header

// 3.x 语法
this.$slots.header

迁移策略

大部分更改已在 2.6 中发布。结果是迁移可以一步完成:

  1. 在 3.x 中,将所有的 this.$scopedSlots 替换为 this.$slots