使用特殊的 ref attribute,可以直接访问底层 DOM 元素。
示例:
<input ref="input">
访问模板引用
1、使用 script setup 书写
示例:
<script setup>
import { ref, onMounted } from 'vue'
// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 同名
const input = ref(null)
onMounted(() => {
input.value.focus()
})
</script>
<template>
<input ref="input" />
</template>
2、使用 setup 函数书写
export default {
setup() {
const input = ref(null)
// ...
return {
input
}
}
}
注意:在组件挂载后才能访问模板引用。
侦听一个模板引用 ref 的变化,依据其值是否为 null 。
示例:
watchEffect(() => {
if (input.value) {
input.value.focus()
} else {
// 此时还未挂载,或此元素已经被卸载(例如通过 v-if 控制)
}
})
v-for 中的模板引用
v-for 中使用模板引用时,对应的 ref 中包含的值是一个数组,它将在元素被挂载后包含对应整个列表的所有元素。
示例:
<script setup>
import { ref, onMounted } from 'vue'
const list = ref([
/* ... */
])
const itemRefs = ref([])
onMounted(() => console.log(itemRefs.value))
</script>
<template>
<ul>
<li v-for="item in list" ref="itemRefs">
{{ item }}
</li>
</ul>
</template>
函数模板引用
ref attribute 还可以绑定为一个函数,会在每次组件更新时都被调用。该函数会收到元素引用作为其第一个参数。
示例:
<input :ref="(el) => { /* 将 el 赋值给一个数据属性或 ref 变量 */ }">
注意:当绑定的元素被卸载时,函数也会被调用一次,此时的 el 参数会是 null。
当然也可以绑定一个组件方法而不是内联函数。
组件上的 ref
ref 也可以使用在子组件上。获取的值是组件实例。
示例:
<script setup>
import { ref, onMounted } from 'vue'
import Child from './Child.vue'
const child = ref(null)
onMounted(() => {
// child.value 是 <Child /> 组件的实例
})
</script>
<template>
<Child ref="child" />
</template>
注意:如果一个子组件使用的是选项式 API 或没有使用 script setup,被引用的组件实例和该子组件的 this 完全一致,这意味着父组件对子组件的每一个属性和方法都有完全的访问权。
script setup 的组件是默认私有的:一个父组件无法访问到一个使用了 script setup 的子组件中的任何东西,除非子组件在其中通过 defineExpose 宏显式暴露。
示例:
<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
// 像 defineExpose 这样的编译器宏不需要导入
defineExpose({
a,
b
})
</script>