-
Notifications
You must be signed in to change notification settings - Fork 0
Open
Labels
Description
Vue setup() 中如何获取组件实例的 ref 对象
参考文章:快速掌握vue3新语法(三) - setup中获取元素引用(ref)
❎ **问题描述:**Vue 文档中对于 setup 的描述中提到:我们无法通过 setup 直接访问得到 refs,这是因为 setup 发生在组件创建阶段 (对应生命周期 beforeCreate 和 create),此时组件实例还没有完全构建。那么我们要怎么获取到组件实例的 ref 对象呢?
解决方法
✅ 在非 setup 钩子中, 我们都是通过 this.$refs
来获取指定元素. 但 setup 中没有"this", "props/emit"都是通过参数来获取, 但是"$refs"并不存在于参数中。
✅ 在 setup 中获取元素引用比较特殊, 分3步骤:
- 定义一个ref变量, 值为null
- 通过"return"暴露ref变量
- 把变量名赋值到元素的ref属性中.
<!--SetupRef.vue-->
<template>
<!-- 第3步-->
<h1 ref="titleRef">标题</h1>
</template>
<script lang="ts">
import { defineComponent,onMounted,ref } from "vue";
export default defineComponent({
name: "SetupRef",
setup(){
// 第1步
const titleRef = ref(null);
onMounted(()=>{
console.log(titleRef.value);
});
// 第2步
return {titleRef};
}
});
</script>
🔆 **注意:**模版中用的是 ref
而不是 :ref
✅ 参考官方文档可知,模板中的 ref 接收的是一个字符串,Vue 会将这个字符串作为属性名挂载在 this.$refs
上,这也就解释了为什么我们声明出来的是变量却不用 v-bind
指令的原因 (模版 ref 参数要的不是对应的变量值,而是变量名)。
❓什么时候用":ref"?
当ref的值是一个函数的时候, 我们必须用":ref", 函数只有一个参数, 那就是当前元素。
<template>
<h1 :ref="getTitleRef">标题</h1>
</template>
<script lang="ts">
import { defineComponent,onMounted,ref } from "vue";
export default defineComponent({
name: "SetupRef",
setup(){
function getTitleRef(el:HTMLElement){
console.log(el);
}
return {getTitleRef}
}
});
</script>
这点在官方文档上也有说明,:ref
接收回调函数,该回调函数接受组件实例作为参数传递。
✅ 在"v-for"中获取多个ref
获取"单个元素(或者组件)的引用"用 ref
即可, 但是如果需要获取循环中的引用, 那么就只能使用 :ref
,同样需要3个步骤:
- 定义函数, 函数需要一个参数, 代表当前元素. 这个函数会被
v-for
循环多次, 每次循环函数都可以获取到当前元素. - 在 setup 的返回值中返回函数.
- 在模板中通过
:ref
指定函数.
<template>
<!-- 第3步, 使用:ref-->
<h1 v-for="n in 3" :key="n" :ref="getTitleRefs">标题{{ n }}</h1>
</template>
<script lang="ts">
import { defineComponent, onMounted, ref } from "vue";
export default defineComponent({
name: "SetupRefVFor",
setup() {
// 第1步, 定义函数
function getTitleRefs(el: HTMLElement) {
console.log(el);
}
// 第2步, 返回函数
return { getTitleRefs };
},
});
</script>
总结来讲,当变量是回调函数时,用 :ref
接收,普通变量用 ref
接受变量名。