内置组合辅助函数
useAttrs、useSlots、useModel、useTemplateRef 与 useId 用于访问组件上下文、建立模型引用和关联 DOM。
useAttrs 与 useSlots
useAttrs() 取得未声明为 props 或 emits 的透传属性。手动绑定到内部元素时,可关闭自动继承,避免属性落在错误的根节点上。
<script setup>
import { useAttrs } from 'vue';
defineOptions({ inheritAttrs: false }); // Vue 3.3+
const attrs = useAttrs();
</script>
<template>
<div class="button-wrapper">
<button v-bind="attrs">提交</button>
</div>
</template>
attrs 始终反映最新值,但不是可直接侦听的响应式对象。useSlots() 返回插槽函数,模板中通常直接使用 $slots 和 <slot> 更简洁。
<header v-if="$slots.header"><slot name="header" /></header>
<main><slot /></main>
在 JavaScript 或渲染函数中可通过 const slots = useSlots() 读取。插槽示例见 插槽。
useModel(Vue 3.4+)
useModel(props, name) 将已声明的模型 prop 与更新事件关联,返回可读写的模型 ref;它不会自动替你声明 props 和 emits。<script setup> 中通常直接用 defineModel()。
<script setup lang="ts">
import { useModel } from 'vue';
const props = defineProps<{ modelValue: string }>();
defineEmits<{ 'update:modelValue': [value: string] }>();
const model = useModel(props, 'modelValue');
</script>
<template>
<input v-model="model" />
</template>
简写:const model = defineModel<string>()。父组件使用 <CustomInput v-model="message" />。
useTemplateRef(Vue 3.5+)
参数对应模板 ref 的字符串名称,引用在挂载后可用,元素卸载时可能为 null。
<script setup lang="ts">
import { onMounted, useTemplateRef } from 'vue';
const input = useTemplateRef<HTMLInputElement>('input');
onMounted(() => input.value?.focus());
</script>
<template>
<input ref="input" />
</template>
较早的版本可使用 ref(null) 与同名模板绑定。
useId(Vue 3.5+)
生成应用内唯一、在 SSR 与客户端水合之间稳定的 ID,适合 label 与 input 的关联,不应用作列表 key。
<script setup>
import { useId } from 'vue';
const id = useId();
</script>
<template>
<label :for="id">用户名</label>
<input :id="id" />
</template>
参考:组合式 API 辅助函数。