Vue3 gets the label element

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:

  1. First  ref set a value for the attribute of the target element, assuming el
  2. Then  setup call  ref the function in the function, the value is  null, and assign it to a variable  . It should be noted here that the variable name must  be the same as the attribute name elwe set for the element ref
  3. 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

Guess you like

Origin blog.csdn.net/weixin_43550562/article/details/128916092