Vue3 和 Vue2 中通过ref 获取标签的不同

Vue2 中使用 ref

<h3 ref="myRefs">
<script>
	export default {
      
      
		mounted(){
      
      
			this.$refs.myRefs.xxxxxx
		}
	}
</script>

Vue3 中使用 ref

ref获取元素:利用ref函数获取组件中的标签元素
功能需求:让输入框自动获取焦点
因为调用setup的时候并没有渲染好dom标签,所以定义的时候需要保留 null 选项

<template>
  <h2>App</h2>
  <input type="text">---
  <input type="text" ref="inputRef">
</template>

<script lang="ts">
import {
      
       onMounted, ref } from 'vue'

export default {
      
      
  setup() {
      
      
    const inputRef = ref<HTMLElement|null>(null)

    onMounted(() => {
      
      
      inputRef.value && inputRef.value.focus()
    })

    return {
      
      
      inputRef
    }
  },
}
</script>

猜你喜欢

转载自blog.csdn.net/weixin_44684357/article/details/132439800