模板 refs 允许你直接获取对真实 DOM 元素(或子组件实例)的引用,当你需要做一些 Vue 的声明式模型无法覆盖的命令式操作时 — 例如 focus 输入框、测量元素或调用子组件的方法。
访问 DOM 元素
vue
<script setup>
import { ref, onMounted } from "vue";
const inputEl = ref(null); // 1. create a ref (initially null)
onMounted(() => {
inputEl.value.focus(); // 3. after mount, .value is the DOM element
});
</script>
<template>
<input ref="inputEl" /> <!-- 2. ref attribute name matches the variable -->
</template>
模式:声明 ,通过元素上的 将其附加,mount 后, 就是真实的 DOM 节点。在 mount 前它是 ,所以在 中(或之后)访问它,而不是在 setup 期间。
