You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue3中能否将属性绑定到组件插槽子元素?基于Vuetify简化绑定

解决方案:自动绑定Vuetify Tooltip激活器属性到插槽子元素

你的思路方向是对的,但直接给<slot>绑定属性不会自动传递给子元素——因为<slot v-bind="props"是传递作用域插槽参数,需要用户在使用时通过v-slot接收后手动绑定。要实现自动绑定到子元素,需要在组件内部处理插槽内容,合并激活器属性与子元素原有属性。

正确的AppTooltip组件实现

// AppTooltip.vue
<script setup lang="ts">
import { useSlots } from 'vue'

const props = defineProps<{ text: string }>()
const slots = useSlots()
</script>

<template>
  <v-tooltip :text="props.text">
    <template #activator="{ props: activatorProps }">
      <!-- 遍历默认插槽内容,为每个子元素合并激活器属性 -->
      <template v-for="node in slots.default?.() || []" :key="node.key || `tooltip-node-${Math.random()}`">
        <component
          :is="node.type"
          v-bind="{ ...node.props, ...activatorProps }"
        >
          <!-- 递归渲染子元素(处理嵌套内容) -->
          <template v-for="child in node.children || []" :key="child.key || `tooltip-child-${Math.random()}`">
            <component :is="child.type" v-bind="child.props">{{ child.children }}</component>
          </template>
        </component>
      </template>
    </template>
  </v-tooltip>
</template>

为什么这样可行

  1. 获取插槽内容:通过useSlots()获取默认插槽的VNode列表
  2. 合并属性:用<component>渲染每个插槽子元素,将子元素原有属性(node.props)与Tooltip激活器需要的属性(activatorProps)合并
  3. 递归渲染:处理子元素内部的嵌套内容,确保整个插槽结构正常渲染

你的期望使用方式完全生效

<AppTooltip text="Save changes">
   <v-btn @click="save">
      Save
   </v-btn>
</AppTooltip>

此时v-btn会自动接收Tooltip激活器所需的鼠标事件、焦点事件等属性,无需手动编写v-bind。

内容的提问来源于stack exchange,提问作者Kromel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 22:14:54