返回

Vue3 组件封装之 Slots、Emit 和 Props 穿透

前端

前言

在团队协作开发中,基于 UI 库二次封装组件是常见需求,尤其当组件需适应项目业务场景时。本文将重点讨论如何在 Vue3 组件封装中实现 Slots、Emit 和 Props 穿透,帮助你灵活处理组件封装中的各种复杂场景。

Slots 穿透

Slots 穿透允许子组件使用父组件定义的插槽内容。在 Vue3 中,使用 <slot> 标签或 $slots 对象访问插槽:

<template>
  <slot name="header"></slot>
  <slot></slot> <!-- default slot -->
</template>

<script>
export default {
  name: 'MyComponent',
  // ...
}
</script>

在父组件中,使用 <component-name> 标签并传入插槽内容:

<template>
  <MyComponent>
    <template #header>自定义头部内容</template>
  </MyComponent>
</template>
</script>

Emit 穿透

Emit 穿透允许子组件触发父组件的事件。在 Vue3 中,使用 $emit 方法触发事件,并通过 v-on 指令侦听事件:

<script>
export default {
  name: 'MyComponent',
  emits: ['my-event'],
  // ...
}
</script>

在子组件中,使用 $emit('my-event', data) 触发事件,并在父组件中使用 v-on:my-event 侦听:

<template>
  <MyComponent @my-event="handleMyEvent"></MyComponent>
</template>

<script>
methods: {
  handleMyEvent(data) {
    // ...
  }
},
</script>
</script>

Props 穿透

Props 穿透允许子组件接收父组件的 Props,即使子组件不是直接子级。

使用 provide/inject API

// 父组件
<script>
export default {
  provide() {
    return {
      sharedProp: '共享 Props'
    }
  },
  // ...
}
</script>
// 子组件
<script>
export default {
  inject: ['sharedProp'],
  // ...
}
</script>

使用 attrsprops

// 父组件
<MyComponent :shared-prop="共享 Props"></MyComponent>
// 子组件
<script>
export default {
  props: ['sharedProp'],
  // ...
}
</script>

结论

通过 Slots、Emit 和 Props 穿透,Vue3 组件封装变得更加灵活,你可以轻松构建复杂组件,满足各种业务场景需求。希望本文对你理解和应用这些概念有所帮助,助你写出更高质量、更可维护的 Vue3 代码。