在 Vue3 中,获取插槽实例的方式与 Vue2 有所不同。可以通过 $slots 属性获取所有插槽内容,然后通过 v-for 指令遍历所有插槽内容,并使用 $refs 属性获取每个插槽的实例。

例如,假设我们有以下组件:

<template>
  <div>
    <slot name='header' ref='headerSlot'></slot>
    <slot name='content' ref='contentSlot'></slot>
    <slot name='footer' ref='footerSlot'></slot>
  </div>
</template>

我们可以在组件内部使用 $slots 属性获取所有插槽内容,然后使用 v-for 指令遍历所有插槽,并使用 $refs 属性获取每个插槽的实例:

<script>
export default {
  mounted() {
    // 获取 header 插槽实例
    const headerSlot = this.$slots.header[0].$refs.headerSlot
    console.log(headerSlot)

    // 获取 content 插槽实例
    const contentSlot = this.$slots.content[0].$refs.contentSlot
    console.log(contentSlot)

    // 获取 footer 插槽实例
    const footerSlot = this.$slots.footer[0].$refs.footerSlot
    console.log(footerSlot)
  }
}
</script>

注意,如果插槽内容为空,$slots 数组将为空数组,因此需要进行判断。此外,如果插槽内容不止一个,需要进行遍历。

Vue3 获取插槽实例 - 完整指南

原文地址: https://www.cveoy.top/t/topic/mU00 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录