English | 中文
A lightweight Vue 3 composable to forward component ref and merge the child's exposed API onto the parent instance. Parent's ref then exposes both the child's expose() and optional extra fields in one place.
- Lightweight – Zero dependencies, minimal footprint
- Type Safe – Full TypeScript support
- Simple API –
useForwardRef(ext?)returns{ forwardRef }, pass it to child'sref - Merge with ext – Optionally merge extra fields onto the parent's exposed object
# npm
npm install vue-use-forward-ref
# yarn
yarn add vue-use-forward-ref
# pnpm
pnpm add vue-use-forward-ref
# bun
bun add vue-use-forward-refUse forwardRef as the child's ref. The parent's ref (e.g. from a grandparent) will then receive the child's exposed API.
<!-- Wrapper.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import { useForwardRef } from 'vue-use-forward-ref';
import Child from './Child.vue';
const { forwardRef } = useForwardRef();
</script>
<template>
<Child :ref="forwardRef" />
</template><!-- App.vue -->
<script setup lang="ts">
import type Child from './Child.vue';
const wrapperRef = useTemplateRef<InstanceType<typeof Child>>('wrapperRef');
</script>
<template>
<Wrapper ref="wrapperRef" />
</template>You can merge additional fields onto the exposed object so the parent ref sees both the child's API and your extra data.
// types.ts
import type { Ref } from 'vue';
import type Child from './Child.vue';
export type WrapperExpose = {
count: Ref<number>;
reset: () => void;
};
export type WrapperInstance = InstanceType<typeof Child> & WrapperExpose;<!-- Wrapper.vue -->
<script setup lang="ts">
import { ref } from 'vue';
import { useForwardRef } from 'vue-use-forward-ref';
import Child from './Child.vue';
import type { WrapperExpose } from './types';
const count = ref(0);
const { forwardRef } = useForwardRef<WrapperExpose>({
count,
reset: () => {
count.value = 0;
}
});
</script>
<template>
<Child :ref="forwardRef" />
</template><!-- App.vue -->
<script setup lang="ts">
import type { WrapperInstance } from './types';
const wrapperRef = useTemplateRef<WrapperInstance>('wrapperRef');
</script>
<template>
<Wrapper ref="wrapperRef" />
</template>Copyright (c) 2026-present REFINIST