Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This is the seventh article in the Vue series. How do I get elements from ref

In vue2. X, you can add the ref=’ XXX ‘attribute to the element and then get the corresponding element in the code through this.$refs.xxx

However, there is no such thing as $refs in VUe3, so elements obtained by the ref attribute in VUe3 cannot be retrieved in vue2’s way

Vue3 requires lifecycle methods for the simple reason that the elements in template are not yet mounted to the page when setup is executed, so they must be retrieved after Mounted.

<template>
  <div ref='box'>I am DIV</div>
</template>
<script>
import {ref,onMounted}
export default{
  setup(){
    let box = ref(null);
    onMounted(() = >{
      console.log(box.value)
    });
    return {box}
  }
}
</script>
Copy the code

As shown in the code above, in VUe3, all lifecycle methods are removed and need to be imported directly. I’m importing onMounted here

When the interface is mounted, the onMounted callback is automatically executed to retrieve dom elements

summary

1. How to use lifecycle functions in compositionAPI?

Import the import of any lifecycle function you need and call it in setup

2. How does VUe3 get elements on the interface through ref attribute?

Template is written the same way as vue2. Add a ref=' XXX 'to the element.

In Setup, you create and expose reactive data

When the element is created to fit, the corresponding response data is assigned a value

Once the reactive data is assigned, you can use the lifecycle method to get the corresponding reactive data, the DOM element, in the lifecycle method