Vue3 tsx 中如何同时注册 ref 并传递字符串 ref 属性到子组件?

Vue3组合式语法中使用tsx , 往一个子组件上注册一个 ref 引用,同时又通过展开运算符... 将一个含有值是字符串的ref属性的 props 传递给子组件,此时子组件上会有2个ref,我该如何在子组件间中得到props中的字符串ref?

代码简单演示:

const nodeRef = ref()
const props = {
    ref:'uuid_xxx',
    //...any more
}
//... more code
return <ChildComp ref="nodeRef" {...props} />

ChildComp 可能是 SFC 也可能是 tsx 组件。

这种设计不友好,但是由于某些原因,目前只能保持现状。

2个 ref ,一个是mounted后赋值为组件实例,一个是想传递到子组件内部的字符串属性。
目前已经做了尝试,无法在子组件中通过 $attrs & useAttrs() 获取到透传的字符串 ref——'uuid_xxx',但其实'uuid_xxx'值已经通过$attrs的方式挂到 ChildComp 根元素的__id__ attribute上了。

<!-- ChildComp 根元素 -->
<div __id__="uuid_xxx" ...more />

我希望能保持此种情况下,获取到该字符串ref属性值('uuid_xxx')。

阅读 2.1k
avatarAI BotBETA

在 Vue 3 中,当使用 ref 作为属性(prop)和 DOM 引用同时存在于同一个组件上时,确实可能会产生混淆。但是,Vue 提供了明确的方式来区分这两者:ref 用于引用组件实例或 DOM 元素,而 props 用于传递数据到子组件。

在你的场景中,你不能直接将 ref 作为 prop 传递给子组件,因为这会覆盖掉用于获取组件实例的 ref。但是,你可以使用不同的 prop 名称来传递字符串 ref。

以下是如何在 Vue 3 的 tsx 中同时注册 ref 并传递一个名为 uuid(或其他你喜欢的名称)的字符串 prop 到子组件的示例:

import { ref, defineComponent } from 'vue'
import ChildComp from './ChildComp.vue' // 假设 ChildComp 是一个 Vue 组件

export default defineComponent({
  setup() {
    const nodeRef = ref(null) // 使用 ref 来获取子组件实例
    const uuid = 'uuid_xxx' // 这是一个普通的 prop 值

    // ... more code

    return () => (
      <ChildComp ref={nodeRef} uuid={uuid} {/* ...otherProps */} />
    )
  }
})

ChildComp 组件中,你可以通过 props 来访问这个 uuid prop:

<!-- ChildComp.vue -->
<template>
  <div :id="uuid"> <!-- 或者使用其他属性,比如 data-uuid,取决于你的用途 -->
    <!-- 组件内容 -->
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'

export default defineComponent({
  props: {
    uuid: {
      type: String,
      required: true
    }
    // ...otherProps
  },
  // ...组件逻辑
})
</script>

注意,在模板中,我们使用 :id 绑定来将 uuid prop 设置为元素的 id 属性。但你也可以选择其他属性名,比如 data-uuid,这取决于你的具体需求。

另外,如果你想在 tsx 中直接操作 DOM 属性(例如,通过 ref 访问 DOM 元素并设置属性),你应该使用 DOM 引用而不是组件引用。但是,由于你已经有一个字符串 prop 用于标识,你可能不需要直接操作 DOM,除非有特定的理由。

3 个回答

不如在子组件访问父组件的props,不要强求

"ref" is a reserved property.
"ref"是保留属性。

其实我很好奇你的props是怎么写的?你的props应该无论如何也没有ref这个属性才对.

以下是在 Vue 3 的 TSX 中同时注册 ref 并传递字符串 ref 属性到子组件的示例代码:

import { defineComponent, ref } from 'vue';

interface Props {
  refName: string;
}

const ParentComponent = defineComponent({
  setup(props: Props) {
    const childRef = ref(null);

    return () => (
      <ChildComponent ref={childRef} refName={props.refName} />
    );
  },
});

const ChildComponent = defineComponent({
  setup(props, { attrs }) {
    console.log(attrs.refName); 
    // 在这里可以使用传递进来的 refName 属性
    return () => <div>Child Component</div>;
  },
});

在上述代码中,在父组件中创建了一个 ref 对象 childRef ,并将其与子组件关联,同时将字符串属性 refName 传递给子组件。在子组件的 setup 函数中,可以通过 attrs 获取到传递进来的属性。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题