The way to use ref to get dom elements in Vue3, Chatgpt's answer

​​​​​​Ininsert image description here
Vue3, refthe method of using to get a DOM element (such as an element in a component) is different from Vue2. In Vue2, we can add an refattribute to this element and use it in the component this.$refsto access this attribute. In Vue3, we need to use refthe functions provided by Vue3 to create a responsive reference, and then pass it as the attribute value of the element. In this way, we can use the function in the component refto get the reference of this element.

Here is a sample code:

<template>
  <div ref="myDiv">Hello Vue</div>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  setup() {
    const myDiv = ref(null)
    
    onMounted(() => {
      console.log(myDiv.value) // <div>Hello Vue</div>
    })

    return {
      myDiv
    }
  }
}
</script>

In the above code, we first used it in the template refand set it to myDiv, so that the reference of this div is assigned to myDivthis responsive reference.

Next, in setup()the function, we use refthe function to create a myDivreactive reference called , and initialize it to null. Then, in onMounted, we myDiv.valueaccessed this reference through , and thus obtained this divelement.

It should be noted that since the component model in Vue3 has changed, we cannot templatedirectly access it this.$refs, but need to setup()use it in the function refto create a responsive reference. At the same time, when we use refa reference to create a DOM element, we need to use it in the template refto bind the reference to the element.

Get Dom elements in the form of Syntactic sugar of Setup:

// 使用ref获取dom元素
const show = ref<null | HTMLElement>(null)
onMounted(() => {
    
    
  console.log("show---", show.value);
})

おすすめ

転載: blog.csdn.net/weixin_44786530/article/details/130620094