In non-setup hooks, we use this.$refs
to get the specified element. But in the last lesson we said that there is no "this" in setup, and "props/emit" are all obtained by parameters, but "$refs" does not exist In the parameters.
Obtaining element references in setup is quite special, divided into 2 steps:
- Define a ref variable with a value of null.
- Expose the ref variable through "return",
Assign the variable name to the ref attribute of the element.
<!--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>
especially emphasizes: uses "ref" instead of ":ref" in the template.<template> <h1 ref="titleRef">标题</h1> </template>
When to use ":ref"?
When the value of ref is a function, we must use ":ref". The function has only one parameter, which is the current element.
<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>
The result is the same as "ref" without ":"
Get multiple refs in "v-for"
You can use "ref" to get the reference of a single element (or component), but if you need to get the reference in the loop, you can only use ":ref".
Three steps are also required:
- To define a function, the function requires one parameter, which represents the current element. This function will be looped multiple times by v-for, and the current element can be obtained each time the loop function is looped.
- Return the function in the return value of setup.
Specify the function by ":ref" in the template.
<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>
WeChat group
Thank you for reading. If you have any questions, you can add me to WeChat. I will pull you into the group .
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。