Vue 3.0 在prop的默认函数中访问this,Vue 3.0 Slot统一

Vue3.0不再支持在prop默认函数中使用`this`,需通过`inject`API访问。Slot在3.x中得到统一,`this.$slots`替代`this.$scopedSlots`,且渲染函数中定义插槽的方式也有所改变。迁移策略主要是将`this.$scopedSlots`替换为`this.$slots`。
摘要由CSDN通过智能技术生成

Vue 3.0 在prop的默认函数中访问this

生成 prop 默认值的工厂函数不再能访问 this

替代方案:

  • 把组件接收到的原始 prop 作为参数传递给默认函数;
  • 注入 API 可以在默认函数中使用。

 
  1. import { inject } from 'vue'
  2. export default {
  3. props: {
  4. theme: {
  5. default (props) {
  6. // `props` 是传递给组件的原始值。
  7. // 在任何类型/默认强制转换之前
  8. // 也可以使用 `inject` 来访问注入的 property
  9. return inject('theme', 'default-theme')
  10. }
  11. }
  12. }
  13. }

Vue 3.0 Slot统一

#概览

此更改统一了 3.x 中的普通 slot 和作用域 slot。

以下是变化的变更总结:

  • this.$slots 现在将 slots 作为函数公开
  • 非兼容:移除 this.$scopedSlots

更多信息,请继续阅读!

#2.x 语法

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

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

此外,在引用作用域 slot 时,可以使用以下方法引用它们:

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

#3.x 语法

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

 
  1. // 3.x Syntax
  2. h(LayoutComponent, {}, {
  3. header: () => h('div', this.header),
  4. content: () => h('div', this.content)
  5. })

当你需要以编程方式引用作用域 slot 时,它们现在被统一到 $slots 选项中。

 
  1. // 2.x 语法
  2. this.$scopedSlots.header
  3. // 3.x 语法
  4. this.$slots.header

#迁移策略

大部分更改已经在 2.6 中发布。因此,迁移可以一步到位:

  1. 在 3.x 中,将所有 this.$scopedSlots 替换为 this.$slots
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值