When I rebuilt the login interface for my personal blog with Vue3.0, it looked like this.

Attach code diagram

<el-form
:model="form"
:rules="rules"
ref="ref_form"
>
</el-form>
Copy the code

Ref =”ref_form” means to get the attributes of the el-form element. Let me focus on the difference between this attribute in Vue2.0 and VUe3.0

What is the ref

Ref is used to register reference information for an element or child component.Copy the code

In Vue2.0 this.$refs operates directly on attribute values,

<div ref="myRef"> < / div >this.$refs.myref to get an instance of the componentCopy the code

Vue3.0

<template>
    <div ref="myRef">Gets a single element</div>
</template>
<script>
import {  defineComponent,ref,onMounted } from 'vue'
export default defineComponent({
    setup(){
        / / bind myRef
        const myRef = ref(null)
        onMounted(() = >{
            // Print the value
            console.log(myRef.value)
        })
        return{
            myRef
        }
    }
})
</script>
Copy the code
Gets multiple DOM elements
<template>
  <div>Gets multiple DOM elements</div>
  <ul class="list">
    <li v-for="(item, index) in arr" :key="index" :ref="setRef">
      {{ item }}
    </li>
  </ul>
</template>

<script>
import { defineComponent, ref, watch } from 'vue';

export default defineComponent({
  setup() {
    const arr = ref([]);

    for (let i = 0; i < 20; i++) {
      arr.value.push(i);
    }

    // Store dom arrays
    const myRef = ref([]);

    const setRef = el= > {
      myRef.value.push(el);
    };

    watch(
      () = > myRef.value,
      () = > {
        console.dir(myRef.value);
      },
      {
        immediate: true});return{ arr, setRef }; }});</script>

<style lang="less" scoped>
.list {
  width: 300px;
  height: 300px;
  margin: 0 auto;
  overflow-y: auto;
}
</style>
Copy the code

conclusion

In Vue3.0, get refs for ref, get refs for ref

  1. Write the ref name in the HTML
  2. The variable is declared in setup
  3. Return Returns the data
  4. Data is accessed through.value

In Vue2.0, it is

  1. Register a REF on a DOM element
  2. Get the attribute through this.$ref