In Vue2, we get elements by giving the element an ref
attribute and then this.$refs.xx
accessing it, but this is no longer applicable in Vue3.
Let's take a look at how to get elements in Vue3:
<template>
<div>
<div ref="el">div元素</div>
</div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
// 创建一个DOM引用,名称必须与元素的ref属性名相同
const el = ref(null)
// 在挂载后才能通过 el 获取到目标元素
onMounted(() => {
el.value.innerHTML = '内容被修改'
})
// 把创建的引用 return 出去
return {el}
}
}
</script>
The operation of obtaining elements is divided into the following steps:
- First
ref
set a value for the attribute of the target element, assumingel
- Then
setup
callref
the function in the function, the value isnull
, and assign it to a variable . It should be noted here that the variable name must be the same as the attribute nameel
we set for the elementref
el
Return (return) the reference variable to the element
Supplement : The set element reference variable can only be accessed after the component is mounted, so it is invalid to operate on the element before mounting