In
Vue3, ref
the 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 ref
attribute to this element and use it in the component this.$refs
to access this attribute. In Vue3, we need to use ref
the 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 ref
to 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 ref
and set it to myDiv
, so that the reference of this div is assigned to myDiv
this responsive reference.
Next, in setup()
the function, we use ref
the function to create a myDiv
reactive reference called , and initialize it to null
. Then, in onMounted
, we myDiv.value
accessed this reference through , and thus obtained this div
element.
It should be noted that since the component model in Vue3 has changed, we cannot template
directly access it this.$refs
, but need to setup()
use it in the function ref
to create a responsive reference. At the same time, when we use ref
a reference to create a DOM element, we need to use it in the template ref
to 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);
})