← 返回首页
Vue3基础教程(二十七)
发表时间:2021-08-12 00:09:46
ref获取元素

利用ref函数获取组件中的标签元素。

实例: 组件加载完毕后,让input输入框自动获取焦点。

<template>
  <h2>ref获取元素</h2>
  用户名:
  <input type="text" ref="inputRef">
</template>

<script lang="ts">
import { onMounted, ref } from 'vue'
/* 
ref获取元素: 利用ref函数获取组件中的标签元素
功能需求: 让输入框自动获取焦点
*/
export default {
  setup() {
    const inputRef = ref<HTMLElement|null>(null)

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

    return {
      inputRef
    }
  },
}
</script>