4

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:

  1. Define a ref variable with a value of null.
  2. Expose the ref variable through "return",
  3. 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>
    

    image.png
    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 ":"
image.png

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:

  1. 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.
  2. Return the function in the return value of setup.
  3. 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>

    image.png

WeChat group

Thank you for reading. If you have any questions, you can add me to WeChat. I will pull you into the group .

To be continued

update, please pay attention to my language bird


铁皮饭盒
5k 声望1.2k 粉丝

喜欢写程序: [链接]